所以我在这里有代码,我期望它严格运行ls -l 5次,但它似乎运行的次数要多得多.我在这做错了什么?我想要运行ls 5次,所以我分叉了5次.也许我不理解等待的概念?我经历了大量的教程,似乎没有人能彻底解决使用fork的多个进程.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main()
{
pid_t pidChilds[5];
int i =0;
for(i = 0; i<5; i++)
{
pid_t cpid = fork();
if(cpid<0)
printf("\n FORKED FAILED");
if(cpid==0)
printf("FORK SUCCESSFUL");
pidChilds[i]=cpid;
}
}
Run Code Online (Sandbox Code Playgroud)
当您在 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;
}
Run Code Online (Sandbox Code Playgroud)