在排名最高的问题答案中:
如果计算机从 0 开始计数,为什么 init 进程的 pid 为 1?
据说,每个进程都有一个 PPID(父进程)。
然而我读到(稍后将提供链接),有很多进程没有父进程。
有人能将这些相互矛盾的陈述放在合理的背景下吗?
答案1
进程总是有一个父进程。然而,当现有进程死亡时,成为新父进程的进程不一定是 PID 1。Linux 是这样做的:
/*
* When we die, we re-parent all our children, and try to:
* 1. give them to another thread in our thread group, if such a member exists
* 2. give it to the first ancestor process which prctl'd itself as a
* child_subreaper for its children (like a service manager)
* 3. give it to the init process (PID 1) in our pid namespace
*/
static struct task_struct *find_new_reaper(struct task_struct *father,
struct task_struct *child_reaper)
{
struct task_struct *thread, *reaper;
thread = find_alive_thread(father);
if (thread)
return thread;
if (father->signal->has_child_subreaper) {
unsigned int ns_level = task_pid(father)->level;
/*
* Find the first ->is_child_subreaper ancestor in our pid_ns.
* We can't check reaper != child_reaper to ensure we do not
* cross the namespaces, the exiting parent could be injected
* by setns() + fork().
* We check pid->level, this is slightly more efficient than
* task_active_pid_ns(reaper) != task_active_pid_ns(father).
*/
for (reaper = father->real_parent;
task_pid(reaper)->level == ns_level;
reaper = reaper->real_parent) {
if (reaper == &init_task)
break;
if (!reaper->signal->is_child_subreaper)
continue;
thread = find_alive_thread(reaper);
if (thread)
return thread;
}
}
return child_reaper;
}
答案2
当一个进程的Parent死亡时,该进程可以说是“没有父进程”。当这种情况发生时,PPID
PID 被设置为 1 init
。
每个进程$STATUS
在退出时都会返回一个值。父进程可以用这个值做一些事情,但它必须存储存储的free
内存$STATUS
,并释放内核中的进程数据。