这是我的示例代码,名为 server.c(为了简单起见,删除了包含)。
int main()
{
for(int i = 0; i < 10; i++) {
fork();
execl("./client", "./client", NULL);
}
if (wait(NULL) == -1)
perror("error with wait");
return 0;
}
这是从上述程序中执行的客户端代码。
int main()
{
printf("This is the child with pid = %d from parent %d", getpid(), getppid());
return 0;
}
现在让我解释一下我认为会发生什么以及我实际得到的输出是什么。
在服务器中,我们进入 for 循环。在第一次迭代中,我们点击了 fork()。此时有两个进程,即父进程和第一个子进程。现在我们从这两个进程中执行一个名为“client”的程序。此客户端代码仅打印一些信息。所以当我运行这个服务器程序时,我应该得到两行,对吗?一行来自 parent ,另一行来自 child ?但是我只打印了一行,在使用 strace 之后我发现只有 parent 在打印东西,而不是 child 。那这是为什么?
是不是因为 child 已经被 exec 了,因为 parent 已经死了(这是正确的术语吗?),所以不能再被收集了?如果是这样, child 会怎样?变成丧尸了吧?它会被init收集吗?即便如此,为什么它在像僵尸一样结束之前不打印出那一行呢?
最佳答案
If stdout is connected to a terminal, it should be line-buffered, so there's no need to flush. And all streams are flushed automatically when they're closed, which happens when the program finishes.
也许你看到两者打印在同一行? 试试这个代码:
#include <stdio.h>
int main(int argc, char **argv) {
printf("This is the child with pid = %d from parent %d\n", getpid(), getppid());
return 0;
}
顺便说一下,您在 printf
中缺少一个 %d
。
关于c - 如果我在 parent 和 child 中 fork 和 exec 会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43380460/