为什么子进程中的睡眠会阻止我的程序?

Why is sleep in a child process blocking my program?

所以我有这个简单的程序,如果 fork 返回的值为“0”意味着子进程正在执行,它会休眠 4 秒,我试过在子进程中使用睡眠但程序被阻止,并且刷新标准输出不起作用... 代码:

#include <stdio.h>
#include <unistd.h>

int main(int argc, char const *argv[]) {
  pid_t value = fork();

  if (value == 0) {
    sleep(4);
  }
  
  printf("Value returned by fork: %d\n", value);
  printf("I'm the process N°%d\n", getpid());
  
  return 0;
}

我 运行 Ubuntu 20.04.3 LTS。

输出:

Value returned by fork: 12618
I'm the process N°12617\
farouk@farouk-HP-Pavilion-Desktop-TP01-1xxx:~/sysexp$  Value returned by fork: 0
I'm the process N°12618

让这个问题有一个可接受的答案。

child 进程没有阻塞 shell。 shell 给出了它的提示,child 在提示后写了一些输出,将光标留在行的开头,没有 shell 提示可见——因为 shell 提示之前已经出现了。

有多种解决方法。

最简单的就是键入一个命令,例如 ps 然后点击 return,注意 shell 会执行它,而 ps 输出不会列出 child 进程。如果您足够快地键入 ps 命令,您可能会在其输出出现之前看到输出中列出的 child。

另一种是修改程序,使其在退出之前等待所有child个进程退出——使用wait()waitpid()。可以在 child 和 parent 中使用相同的代码,因为 child 没有自己的 children。对等待函数的调用将 return 立即出现 'no more children' 状态(错误)。

您可以在评论中找到对所有这些的广泛讨论 — 我选择将其作为社区维基答案,因为评论中有很多 activity这个答案的要点。