鍍金池/ 問答/Python  C  Linux/ 為什么下面這段代碼不會產(chǎn)生大量的僵尸進程??

為什么下面這段代碼不會產(chǎn)生大量的僵尸進程??

代碼如下,我覺得補上幾張圖吧。真的出現(xiàn)了這個奇怪的問題。
照理說應該會產(chǎn)生大量的僵尸進程的丫??墒俏也榭戳诉M程卻只有一個當下的僵尸進程。為什么呢?
系統(tǒng)是Ubuntu16.04,python版本是3.5

代碼一

import multiprocessing as mp
import os
import time

def pro():
    print ("os.pid is ", os.getpid())

if __name__ == '__main__':
    print ("parent ", os.getpid())
    while True:
            p = mp.Process(target = pro)
            p.start()
            time.sleep(1)

代碼一圖示:
代碼一

代碼二

如果換成用C來編寫一段類似的代碼,卻會產(chǎn)生大量的子進程。

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

int main()
{
    pid_t pid;
    while (1){
        pid = fork();
        if (pid < 0){
            puts("fock error");
            exit(1);
        }
        else if(pid == 0){
            printf("I am a Child Process, pid is %d.\n", getpid());
            sleep(1);
            exit(1);
        }
        else
            sleep(3);
    }
    return 0;
}

代碼二圖示:
代碼二圖示

代碼三

用python繼續(xù)寫一段沒有循環(huán)的代碼也一樣會產(chǎn)生一個僵尸進程

from multiprocessing import Process
import os
import time

def run():
    print ("pid is ", os.getpid())

p = Process(target = run)
p.start()
time.sleep(100)

代碼三圖示:
代碼三圖示

為什么會這樣丫???僵尸進程的產(chǎn)生原因我應該沒理解錯的吧。就是父進程在子進程死后沒有去理會子進程導致的問題。但是代碼一和代碼二三好像沒有什么區(qū)別丫,可是代碼一卻沒有產(chǎn)生一堆的僵尸進程,真的不是很理解了。

回答
編輯回答
編輯回答
愚念

因為你的進程執(zhí)行完了那一行 print 之后就結束了,如果你的 pro 方法里是一個死循環(huán)的話應該就會有大量僵尸進程了。

2017年1月16日 03:09
編輯回答
柚稚

第一段程序,你在pro函數(shù)里增加個sleep,就能看到有多個子進程了。

def pro():
    print ("os.pid is ", os.getpid())
    time.sleep(3)
2018年6月8日 11:34
編輯回答
胭脂淚

謝邀,三段代碼。第一段比較好理解吧。新建的進程只有一個print,執(zhí)行完就會結束了,python會自動回收這個子進程,沒有僵尸進程的,你看到的應該是主進程吧。

第二段C代碼,死循環(huán)中有一個 fork 。然后子進程調用 exit 后成為了一個僵尸進程。父進程一直不會關閉。
所以就不斷產(chǎn)生僵尸進程了啊,正確的做法是在父進程中回收子進程:

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

int main()
{
    pid_t pid;
    int status;
    while (1){
        pid = fork();
        if (pid < 0){
            puts("fock error");
            exit(1);
        }
        else if(pid == 0){
            printf("I am a Child Process, pid is %d.\n", getpid());
            sleep(1);
            exit(1);
        }
        else{
            wait(&status); // 回收子進程
            sleep(3);
        }
    }
    return 0;
}

第三段,額,同第一段,你看到的應該就是主線程了。

---- 分割線 ------
根據(jù)題主的截圖,我執(zhí)行了一下,還真是會有一個僵尸進程,慚愧,居然和印象中的不一樣。但是這個僵尸進程只有一個,不會像C語言那段代碼一樣是不斷產(chǎn)生的。于是我就去看看python是如何處理子進程的。mutilprossing.Process 繼承自 BaseProcess 文件在 Lib/mutilprossing/process.py 中,我們看看它的start方法:

_children = set()

class BaseProcess(object):
    def start(self):
        self._check_closed()
        assert self._popen is None, 'cannot start a process twice'
        assert self._parent_pid == os.getpid(), \
               'can only start a process object created by current process'
        assert not _current_process._config.get('daemon'), \
               'daemonic processes are not allowed to have children'
        _cleanup()
        self._popen = self._Popen(self)
        self._sentinel = self._popen.sentinel
        # Avoid a refcycle if the target function holds an indirect
        # reference to the process object (see bpo-30775)
        del self._target, self._args, self._kwargs
        _children.add(self)

_children 是一個全局的集合變量,保存著所有 BaseProcess 實例,start 函數(shù)末尾處 _children.add(self) 將進程對象放入。又注意到 _cleanup() 函數(shù):

def _cleanup():
    # check for processes which have finished
    for p in list(_children):
        if p._popen.poll() is not None:
            _children.discard(p)

這下就清楚了,python在子進程start中將進程放入集合,子進程可能長時間運行,因此這個集合上的進程會有很多狀態(tài),而為了防止過多僵尸進程導致資源占用,python會在下一個子進程 start 時清理僵尸進程。所以,最后一個子進程在自身程序運行完畢后就變成僵尸進程,它在等待下一個子進程start時被清理。所以 ps 上總有一個僵尸進程,但這個僵尸進程的進程id一直在變化。

python確實做到自動清理了,是我自己混淆了,看來以后要多多看看源碼才行了。

關于C語言的僵尸進程上面已經(jīng)回答了。如果子進程先于父進程退出, 同時父進程又沒有調用 wait/waitpid ,則該子進程將成為僵尸進程。

2017年10月7日 21:15
編輯回答
舊顏

首先是,主進程退出,子進程或子線程都會退出,這個沒什么問題。
再就是下面這段代碼,應該是不會產(chǎn)生僵死進程的,因為子進程run方法運行的很快,而主進程sleep 100s,所以不會產(chǎn)生主進程先退出(不知道你是怎么看到有僵死進程的)

from multiprocessing import Process
import os
import time

def run():
    print ("pid is ", os.getpid())

p = Process(target = run)
p.start()
time.sleep(100)
2018年3月13日 14:41