系统调用 execve

main.c

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

char * argv[]={ "arg1","arg2", NULL };
char * envp[] = { "PATH=/bin", "HOME=/root", NULL };

int main()
{
        printf("main pid = %d\n", getpid());
        int pid;
        if(!(pid=fork()))
        {
                printf("execve pid = %d\n", getpid());
                // 执行hello不创建新进程  hello的pid和这个子进程pid相同
                execve("./hello",argv,envp);
        }
        while(pid != wait(NULL)) /* do nothing */;
        printf("main end\n");
        return 0;
}

hello.c

#include <stdio.h>
#include <unistd.h>

int main(int argc, char **argv, char **envp)
{
        printf("hello program start\n");
        pid_t pid = getpid();
        printf("helllo pid = %d\n", pid);
        int i;
        for(i=0;i<argc;i++)
                printf("argv: %s\n",argv[i]);

        while (*envp != NULL)
                printf("arge: %s\n",*envp++);

        printf("hello program end\n");
        return 0;
}

编译运行

gcc mian.c -o main
gcc hello.c -o hello
./main

执行结果

main pid = 4408
execve pid = 4410
hello program start
helllo pid = 4410
argv: arg1
argv: arg2
arge: PATH=/bin
arge: HOME=/root
hello program end
main end

link

posted @ 2022-11-18 16:17  zkx98  阅读(66)  评论(0编辑  收藏  举报