是否存在沒有父進程的進程?

是否存在沒有父進程的進程?

在排名最高的問題答案中:

如果計算機從 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死亡時,該進程可以說是「沒有父進程」。當這種情況發生時,PPIDPID 被設定為 1 init

每個進程$STATUS 在退出時都會傳回一個值。父進程可以用這個值做一些事情,但它必須儲存儲存的free內存$STATUS,並釋放核心中的進程資料。

相關內容