最后是exec()系统调用,它也是创建进程API 的一个重要部分1。这个系统调用可以让子进程执行与父进程不同的程序。例如,在p2.c 中调用fork(),这只是在你想运行相同程序的拷贝时有用。但时,我们常常想运行不同的程序,exec()正好做这样的事(见图5.3)。
t> ./p3
world (pid:29383)
, I am child (pid:29384)
29 107 1030 p3.c
, I am parent of 29384 (wc:29384) (pid:29383)
t>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
int
main(int argc, char *argv[])
{
printf("hello world (pid:%d)\n", (int) getpid());
int rc = fork();
if (rc < 0) { // fork failed; exit
fprintf(stderr, "fork failed\n");
exit(1);
} else if (rc == 0) { // child (new process)
printf("hello, I am child (pid:%d)\n", (int) getpid());
char *myargs[3];
myargs[0] = strdup("wc"); // program: "wc" (word count)
myargs[1] = strdup("p3.c"); // argument: file to count
myargs[2] = NULL; // marks end of array
execvp(myargs[0], myargs); // runs word count
printf("this shouldn't print out");
} else { // parent goes down this path (main)
int wc = wait(NULL);
printf("hello, I am parent of %d (wc:%d) (pid:%d)\n",
rc, wc, (int) getpid());
}
return 0;
}
图5.3 调用fork()、wait()和exec()(p3.c)
在这个例子中,子进程调用execvp()来运行字符计数程序wc。实际上,它针对源代码文件p3.c 运行wc,从而告诉我们该文件有多少行、多少单词,以及多少字节。
fork()系统调用很奇怪,它的伙伴exec()也不一般。给定可执行程序的名称(如wc)及需要的参数(如p3.c)后,exec()会从可执行程序中加载代码和静态数据,并用它覆写自己的代码段(以及静态数据),堆、栈及其他内存空间也会被重新初始化。然后操作系统就执行该程序,将参数通过argv 传递给该进程。因此,它并没有创建新进程,而是直接将当前运行的程序(以前的p3)替换为不同的运行程序(wc)。子进程执行exec()之后,几乎就像p3.c 从未运行过一样。对exec()的成功调用永远不会返回。
-
实际上,exec()有几种变体:execl()、execle()、execlp()、execv()和execvp()。请阅读man 手册以了解更多信息。 ↩