當您在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;
}
提示:如果cpid == 0,你認爲還有什麼你忘記了嗎? – 2013-03-07 14:43:19
@NicholasWilson不是我能想到的。 (我在做什麼錯了?) – NoNameY0 2013-03-07 14:47:16
Forkbomb,ftw!:D – Carsten 2013-03-07 15:24:29