Outline
- 1.exec函数族
- 2.测试
=================================================================================================
1. exec函数族
exec函数通常与fork函数一起使用,在fork子进程以后,立刻调用exec。
exec函数的作用是将调用进程完全替换为一个新的进程,即将由fork产生的子进程独立成一个新的进程,该进程执行由exec函数第一个参数指定的程序文件。
- int execl( char *pathname,char *arg0,char *arg1,...,char *argn,NULL)
-
int execle( char *pathname,char *arg0,char *arg1,...,char *argn,NULL,char *envp[])
-
int execlp( char *filename,char *arg0,char *arg1,...,NULL)
-
-
int execv( char *pathname,char *argv[])
-
int execve( char *pathname,char *argv[],char *envp[])
-
int execvp( char *filename,char *argv[])
path和filename的区别就是:/path/program 和 program,后者在环境变量PATH中搜索program,当然,后者也可以直接写成/path/program
2. 测试
exec.c
- #include <stdio.h>
-
#include <stdlib.h>
-
#include <unistd.h>
-
-
int main()
-
{
-
pid_t pid;
-
-
printf("parent process: pid is %d\n", getpid());
-
fflush(stdout);
-
-
pid = fork();
-
if (pid < 0)
-
printf("fork failed.\n");
-
else if (pid == 0) {
-
printf("child process: pid is %d, ppid is %d\n", getpid(), getppid());
-
execl("./test", (char *)0);
-
}
-
-
sleep(1);
-
printf("over\n");
-
return 0;
-
}
test.c
- #include <stdio.h>
-
#include <unistd.h>
-
-
int main()
-
{
-
printf("after execl, child process: pid is %d, ppid is %d\n", getpid(), getppid());
-
return 0;
-
}
输出:
- parent process: pid is 12305
-
child process: pid is 12306, ppid is 12305
-
after execl, child process: pid is 12306, ppid is 12305
-
over
阅读(1410) | 评论(0) | 转发(0) |