c - 为什么 fork() 的输出是特定顺序的?

标签 c linux operating-system printf fork

我正在做一些操作系统 101 作业并研究一些 C 代码。

我是 C 和 Linux 的新手,所以我有这个可能不寻常的问题。我必须检查一个 C 程序才能弄清楚它启动了多少个进程。所以我阅读了很多书并修改了原始代码以回答所有问题。

#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>

int main (void)
{
   printf("Start ID %d\n\n", getpid());

   printf("1.fork() from ");   
   printf("ID: %d\n", getpid());
   fflush(stdout);
   fork();

   printf("2.fork() from ");
   printf("ID: %d my parent is ID %d\n", getpid(), getppid());   
   fflush(stdout);
   fork();

   printf("3.fork() from ");
   printf("ID: %d my parent is ID %d\n", getpid(), getppid());  
   fflush(stdout);
   fork();

   sleep(2);   
   printf("%d finished. Good Night!\n", getpid());
   return EXIT_SUCCESS;
}

有一件事我不明白。为什么 printf() 的输出按以下顺序在 fork 之前:

1.fork() from ID: 3124
2.fork() from ID: 3124 my parent is ID 2215
3.fork() from ID: 3124 my parent is ID 2215
3.fork() from ID: 3126 my parent is ID 3124
2.fork() from ID: 3125 my parent is ID 3124
3.fork() from ID: 3125 my parent is ID 3124
3.fork() from ID: 3129 my parent is ID 3125

我希望

1.fork() from ID: 3124
2.fork() from ID: 3124 my parent is ID 2215
3.fork() from ID: 3124 my parent is ID 2215
2.fork() from ID: 3125 my parent is ID 3124
3.fork() from ID: 3125 my parent is ID 3124
3.fork() from ID: 3126 my parent is ID 3124 
3.fork() from ID: 3125 my parent is ID 3124
3.fork() from ID: 3129 my parent is ID 3125

因为 PID 3124 使用第一个 fork() 启动 PID 3125,另外两个子进程都使用第二个,依此类推。 CPU 不是按照创建的顺序执行进程吗?这不是我的作业的一部分,但我仍然对此感到好奇。

最佳答案

您无法真正确定哪个进程将首先执行。就像 HackerBoss 所说的 printf也可以影响这个顺序。

假设您的主程序 pid ( 3124) 生成子 3125 .生成 child 后,父亲和 child 都需要调用以下指令:

printf("2.fork() from ");

此时有两个方向:

  1. 父亲 3124调用 printf
  2. child 3125调用 printf

printf需要 I/O scheduling这取决于 process priorityresource state 上(可能有另一个进程已经在使用该资源,使其成为 busy resource )。

所以在你的程序中看起来像父亲3124首先获得对资源的访问权并继续执行直到下一个 fork ,其中子节点 3126生成。

此时有同一个问题:我该往哪个方向走?下一条指令是:

printf("3.fork() from ");

方向是:

  1. 父亲 3124调用 printf
  2. child 3126调用 printf

从您的程序看来,第一个调用它的进程是子进程 3126 .

所以实际上 printf不向您保证流程生成顺序。 I/O scheduling 既然是透明的有效,更好的方法是通过包装 fork 将值存储在每个进程不同的特定地址中在if声明:

pid=fork();
if (pid == 0) {
    //child process
} else {
    //father process
}

这样你可以更好地了解 process scheduler 是什么正在做,因为它实际上可能是 process scheduler在另一个之前启动一个 child ,有很多调度算法。此时OS您正在运行还会影响流程执行顺序,具体取决于所使用的算法。

关于c - 为什么 fork() 的输出是特定顺序的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52795848/

相关文章:

linux - 使用 libblkid 查找分区的 UUID

c - 子进程向管道写入内容后无法从管道读取

assembly - 无法在 16 位实模式汇编中清除整个屏幕

c - 使用 pthread 模拟循环

c - 安装/卸载 C Windows 服务

linux - 如何在恢复实例时删除丢失的 dbf

c - malloc 函数在 C 中如何工作?

c++ - 如何防止 C++ 或 native 编译代码中的 I/O 访问

c - 这个什么时候执行?

Visual Studio Code、gcc、Mac 的 C/C++ 扩展 : "variable uint32_t is not a type name"