我正在学习 Linux 中的 fork(),这是我的程序:
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 int main(void){
5 int pid;
6 pid = fork();
7 if(pid < 0){
8 exit(1);
9 }
10 if(pid == 0){
11 fork();
12 fork();
13 printf("pid:%d ppid:%d\n",getpid(),getppid());
14 exit(0);
15 }
16 else{
17 printf("parent pid:%d ppid:%d\n",getpid(),getppid());
18 exit(0);
19 }
20
21 }
有时它工作得很好,结果是这样的:
./test1.out
parent pid:27596 ppid:21425
pid:27599 ppid:27597
pid:27597 ppid:27596
pid:27598 ppid:27597
pid:27600 ppid:27598
但结果并不一致,通常情况下是这样的:
parent pid:27566 ppid:21425
pid:27567 ppid:27566
pid:27568 ppid:27567
pid:27569 ppid:1599
pid:27570 ppid:1599
这对我来说毫无意义,所以我输入了 $ps aux 来找出进程 1599 是什么:(删除了一些列)
USER PID VSZ RSS STAT START COMMAND
linux 1599 63236 6316 Ss 09:03 /lib/systemd/systemd --user
谁能帮我解决问题?
最佳答案
您观察到的“不一致”是因为有时父进程在其子进程终止之前退出。因此,这些子进程变为 "orphans"作为他们的 父进程不是waiting为他们。结果,它们被“重新设置”为 init 进程。 虽然传统上“init”进程的进程 ID 为 1,但并不总是如此。 POSIX将其保留为实现定义:
The parent process ID of all of the existing child processes and zombie processes of the calling process shall be set to the process ID of an implementation-defined system process. That is, these processes shall be inherited by a special system process.
因此您将特定的 PID 视为父进程(在您的示例中为 1599),它恰好是 Linux 上的“init”进程。 systemd是 Debian Linux 发行版中使用的 init 变体 - 它遵循稍微复杂的实现。
从本质上讲,你观察到的是很正常的。理想情况下,您应该收获所有进程以避免 zombie processes .
关于c - 为什么我 fork 的进程将 systemd 作为它们的父进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40424031/