c-Fork()并使用wait()等待子进程完成



我有一个程序,可以将文件的内容复制到Destination中。

我正在努力实现选项-j因此程序在子进程中进行复制。-j的数字参数必须大于或等于2。

  • 使用-j 2,同时总共有两个进程一个协调器和执行复制的1个
  • 使用-j 3,总共有三个进程同时执行:1个协调器2个执行复制
  • 对于-j 10,总共有十个进程同时执行:1个协调器9个执行复制
  • 如果要复制的j-1文件个以上,则协调器将等待复制结束,然后再开始下一个复制过程

那么,为了回答这个问题:在第二个分叉点应该什么时候完成等待

答案:在分叉((之后,一旦它的一个孩子死了,它就会复活。父母应该能够看到他有多少孩子,一旦低于限制,他就会给一个新的孩子分配

./prog -j 3 t/a/a t/a/b t/a/c t/b,我们想将a和b的内容复制到t/b/


|   |                 |      |   |                   |
|   |                 |      |   |                   |
|   |                 |      |   |                   |
|   |----t/a/a->t/b/a-|      |   |                   |
|                            |   |                   |
-----t/a/b -> t/b/c---------|----                   |
------t/a/c -> t/b/c-----

我尝试过的:

//PSEUDO CODE
while (nbFiles > 0)
{ // Loop through files
for (i = 0; i < nbprocess; i++)//.... loop of the process.
{
pid = fork();
wait(&status);
if (pid == 0)
{
break;
}
}
if (pid == 0)
{
// do the task
}
if (pid < 0)
{
perror("erreur de fork");
exit(1);
}
}

我已经忘记了这个问题,但我不够清楚,我很抱歉我是这个平台的新手,请随时要求进一步澄清。

如果像在伪代码中那样在fork之后执行wait,则在父级和子级上执行wait

在子进程上,这可能会导致未定义的行为(手册页没有提到这一点(,因为此时子进程将没有任何子进程可等待。

在父级,您等待子级,然后启动下一个子级。所以您是按顺序执行它们的,所以为什么还要麻烦使用fork呢。

为了利用并行性,您需要一个接一个地分叉所有子级,并将子级pid存储在一个数组中。然后,在启动子级之后,您将对子级的每个pid使用waitpid。使用waitpid是因为有了waitpid,您可以控制等待的孩子

//PSEUDO CODE
while (nbFiles > 0)
{ // Loop through files
pid_t children[nbprocess]; 
// or malloc(nbprocess * sizeof *children) for 
// very large nbprocess, but don't forget to do free if
// you use it
for (i = 0; i < nbprocess; i++)//.... loop of the process.
{
pid = fork();
if (pid == 0)
{
// CHILD process, do the task
// end with exit
exit(0); // or whatever status
} else if (pid > 0) {
// PARENT aka orchestrator
children[i] = pid;
} else {
perror("erreur de fork");
exit(1);
}
}
int wstatus;
for (i = 0; i < nbprocess; i++)//.... loop of the process.
{
// wait for the children one at a time
waitpid(children[i], &wstatus, 0);
int exit_status = WEXITSTATUS(wstatus);
printf("The child #%d exited with status %d", i, exit_status);
}
}

或者,当你不在乎订单或等待:

int wstatus;
for (i = 0; i < nbprocess; i++)//.... loop of the process.
{
// wait for the children one at a time
waitpid(-1, &wstatus, 0);
int exit_status = WEXITSTATUS(wstatus);
printf("A child exited with status %d", exit_status);
}

正如Dúthomhas在评论中提到的那样,父母是的指挥

最新更新