我不明白应该在哪里使用 wait(NULL) 或 while(pid = wait(&status))>0)。我很困惑,我得到了奇怪的结果,请帮忙!
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main (int argc, char *argv[]) {
pid_t childpid = 0;
int i, n;
if (argc != 2){ /* check for valid number of command-line arguments */
fprintf(stderr, "Usage: %s processes\n", argv[0]);
return 1;
}
n = atoi(argv[1]);
for (i = 1; i < n; i++)
if ((childpid = fork()) <= 0)
break;
fprintf(stderr, "i:%d process ID:%ld parent ID:%ld child ID:%ld\n",
i, (long)getpid(), (long)getppid(), (long)childpid);
return 0;
}
您将如何修改此代码,以便原始进程在所有子进程退出后打印出其信息?
您将如何修改此代码,以便进程在其子进程退出后打印其信息?
最佳答案
同样的修改可以完成这两项工作。
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main (int argc, char *argv[])
{
pid_t childpid = 0;
int i, n;
if (argc != 2)
{ /* check for valid number of command-line arguments */
fprintf(stderr, "Usage: %s processes\n", argv[0]);
return 1;
}
n = atoi(argv[1]);
for (i = 1; i < n; i++)
{
if ((childpid = fork()) <= 0)
break;
}
int corpse;
int status;
while ((corpse = wait(&status)) > 0)
{
fprintf(stderr, "%d: child %d exited with status 0x%.4X\n",
(int)getpid(), corpse, status);
}
fprintf(stderr, "i:%d process ID:%ld parent ID:%ld child ID:%ld\n",
i, (long)getpid(), (long)getppid(), (long)childpid);
return 0;
}
当子进程执行 wait()
时,它会立即失败,因为没有要等待的孙子进程。因此, child 在“它的 child ”(全部为零)退出后打印它的输出。
当父进程执行 wait()
循环时,它会在信息可用时报告每个子进程,然后打印自己的信息。
你的 child 一般不止一个,所以第二个问题有点模棱两可。但是,如果您希望它等待一个 child (并且您不关心是哪个 child ),则移除 wait()
周围的循环。如果您关心哪个 child ,请使用 waitpid()
而不仅仅是 wait()
。
您可以通过在子进程中返回 i
或根据 i
计算的数字来使输出更有趣。请注意,在 fork 循环从 1
而不是 0
运行之前,因此如果您在命令行上指定 4
,您将获得 3 个子进程以及原始父进程。
关于c - Fork(),等待所有子进程完成 vs 等待一个子进程完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50920031/