我正在做一些操作系统 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 ");
此时有两个方向:
- 父亲
3124
调用printf
- child
3125
调用printf
自 printf
需要 I/O scheduling
这取决于 process priority
在 resource state
上(可能有另一个进程已经在使用该资源,使其成为 busy resource
)。
所以在你的程序中看起来像父亲3124
首先获得对资源的访问权并继续执行直到下一个 fork ,其中子节点 3126
生成。
此时有同一个问题:我该往哪个方向走?下一条指令是:
printf("3.fork() from ");
方向是:
- 父亲
3124
调用printf
- 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/