【问题标题】:Prompt in terminal prints out before finishing print statements for forks()在完成 forks() 的打印语句之前,终端中的提示会打印出来
【发布时间】:2021-09-28 07:51:32
【问题描述】:

我对 fork() 进程和下面给出的代码非常陌生

#include <stdio.h>
#include <unistd.h>
int main()
{
int i;
int n = 4;
for(i=0; i<n; i++)
   fork();
printf("hello\n");
return 0;
}

打印出类似的东西

cse [prompt] ./Program1
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
cse [prompt] hello
hello
hello
hello
hello
hello

为什么在打印完所有的 hello 之前又再次打印出提示?这对我来说真的没有意义。

【问题讨论】:

  • shell 在打印提示之前只等待第一个进程完成。它不会跟踪您的代码创建的子进程,因此当第一个进程终止时,这些子进程可能仍在运行。如果您希望代码等待所有子进程完成,则需要在代码中添加 wait 调用。
  • 请注意,您的代码是一个迷你分叉炸弹。每个子进程也在调用fork,它们的子进程也是如此,依此类推。不确定这是否是您的意图。
  • 也许把精力花在学习 pthread 上会更好。 fork() 有点过时,我们可以从中看出,它拥有有史以来设计的最脆弱的 API 之一。它主要用于程序员装腔作势综合症,而不是实际需要创建一个与当前进程相同的新进程。大多数时候,线程是正确的解决方案。

标签: c fork


【解决方案1】:

保存 FORK() 返回的每个 PID。

然后对每个子进程使用函数waitpid(),这样主进程直到所有子进程(子进程)都退出后才退出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 2017-06-13
    相关资源
    最近更新 更多