【问题标题】:Determining how many processes run using fork确定使用 fork 运行的进程数
【发布时间】:2020-02-02 02:38:48
【问题描述】:

我有这个sn-p 代码,我想确定有多少进程run_morecompute。我正在学习操作系统,但我正在为分叉的概念而苦苦挣扎。

谢谢

void run_morecompute(int i){
   printf("hello world");
}
void run_compute(int i) {
    int cpid = fork();
    if (cpid == 0)
    run_morecompute(i);
}

int main (){
   int pid;
   for (int i = 0; i < 4; i++) {
      pid = fork();
      if (pid == 0){
        printf("\n%d",i);
        run_compute(i);
      }
   }
}

【问题讨论】:

  • \n放在 printf 格式字符串的末尾,而不是开头。 Stdout 是行缓冲的,因此在您打印换行符之前不会打印该行。
  • 为什么run_morecompute()不使用i参数?
  • 你不能只计算hello world 被打印的次数吗?你有什么问题?

标签: c process operating-system fork


【解决方案1】:

如果你改变了

printf("hello world");

printf("hello world from %d", getpid());

它将进程 ID 添加到输出中。它可以帮助您了解创建了多少进程。

我建议将 main 中的循环更改为仅调用 run_morecompute() 直到您掌握正在发生的事情。 run_compute() 中的额外 fork() 使事情变得更加复杂。

顶级进程派生出 4 个调用 run_compute() 的子进程。然后这 4 个孩子成为父母,并分别生出 3 个孩子。然后这 12 个孩子分别再分叉 2 个进程……等等。

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多