当你在 C 中使用 fork 时,你必须想象进程代码和状态被复制到一个新进程中,此时它从停止的地方开始执行。
当你在 C 中使用 exec 时,你不得不想象如果调用成功,整个进程都会被替换掉。
这是您的代码,重新编写以产生预期的行为。请阅读评论。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main()
{
pid_t cpid;
pid_t pidChildren[5];
int i;
for (i = 0; i < 5; i++)
{
cpid = fork();
if (cpid < 0) {
printf("fork failed\n");
} else if (cpid == 0) {
/* If we arrive here, we are now in a copy of the
state and code of the parent process. */
printf("fork successful\n");
break;
} else {
/* We are still in the parent process. */
pidChildren[i] = cpid;
}
}
if (cpid == 0) {
/* We are in one of the children;
we don't know which one. */
char *cmd[] = {"ls", "-l", NULL};
/* If execvp is successful, this process will be
replaced by ls. */
if (execvp(cmd[0], cmd) < 0) {
printf("execvp failed\n");
return -1;
}
}
/* We expect that only the parent arrives here. */
int exitStatus = 0;
for (i = 0; i < 5; i++) {
waitpid(pidChildren[i], &exitStatus, 0);
printf("Child %d exited with status %d\n", i, exitStatus);
}
return 0;
}