python 并發subprocess.Popen的坑

woshi123 7年前發布 | 35K 次閱讀 Python 并發 Python開發

表現

一個父進程里多個線程并發地調用 subprocess.Popen 來創建子進程的時候, 會有幾率出現 Popen 長時間不返回的情況.

這個問題是由于fd被多個子進程同時繼承導致的.

重現問題的代碼

下面這個小程序啟動2個線程, 每個線程各自(通過 subprocess.Popen )啟動一個子進程, 一個子進程執行 echo 1 后就直接返回; 另一個子進程啟動后, sleep 0.03 秒后返回.

程序里統計了2個調用 Popen 花的時間, 運行后可以發現, echo的進程有時啟動很快(小于預期的0.01秒, 僅僅是啟動, 不包括執行時間), 有時會很慢(超過0.03秒), 剛好和另一個sleep的進程執行時間吻合. 調大sleep子進程的時間可以看到echo也會同樣有幾率返回慢.

> cat slow.py

import threading import subprocess import time

def _open(cmd, expect):

t0 = time.time()
proc = subprocess.Popen(
        cmd,
        shell=True,
        # # without this line, some Popen does not return at once as expected
        # close_fds=True,
        stderr=subprocess.PIPE,
        stdout=subprocess.PIPE)

spent = time.time() - t0
if spent > expect:
    print cmd + ' spent: ' + str(spent)

proc.wait()


for ii in range(100): ths = [ threading.Thread(target=_open, args=('echo 1', 0.01)), threading.Thread(target=_open, args=('sleep 0.03', 0.05)), ]

for th in ths:
    th.start()

for th in ths:
    th.join()

> python2 slow.py

echo 1 spent: 0.0381829738617

echo 1 spent: 0.041118144989

echo 1 spent: 0.0417079925537

echo 1 spent: 0.0421600341797

echo 1 spent: 0.039479970932

...</pre>

運行環境:

# uname -a
Linux ** 3.10.0-327.el7.x86_64 #1 SMP Thu Nov 19 22:10:57 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux

# python2 --version
Python 2.7.5

# cat /etc/*-release
CentOS Linux release 7.2.1511 (Core)

解決方法

Popen 時加上 close_fds=True , 保證fd不會被多個子進程繼承.

proc = subprocess.Popen(
        cmd,
        close_fds=True, # here
        ...
        )

原因

直接原因是因為有并發時, Popen中創建的pipe沒有被關閉, 導致父進程認為子進程還沒啟動成功而一直阻塞.

這里的 Popen 的過程, 包括:

  • 父進程創建通信的管道(調用 os.pipe() )
  • fork子進程
  • 父進程通過pipe阻塞讀取子進程的啟動后的錯誤消息, 確認失敗;
  • 或讀取到EOF(pipe在子進程exec時被關閉), 確認成功.

Popen 調用的最核心的代碼是 subprocess.py 中的 _execute_child , 問題的原因可以從下面這段簡化版的代碼中看到:

def _execute_child(self, args, executable, preexec_fn, close_fds,
                   cwd, env, universal_newlines,
                   startupinfo, creationflags, shell, to_close,
                   p2cread, p2cwrite,
                   c2pread, c2pwrite,
                   errread, errwrite):
    # 1) 創建pipe用于父子進程通信...
    errpipe_read, errpipe_write = self.pipe_cloexec()
    try:
        try:
            # 2) 3)
            self.pid = os.fork()
            if self.pid == 0:
                # 子進程流程
                try:
                    # 5) 子進程關閉讀的pipe: 不需要接受父進程的消息
                    os.close(errpipe_read)

                    # 如果需要, 子進程關閉所有打開的文件描述符.
                    # 只留下用于告之父進程錯誤的pipe
                    if close_fds:
                        self._close_fds(but=errpipe_write)

                    # 7) 子進程加載程序
                    os.execvp(executable, args)

                except:
                    exc_type, exc_value, tb = sys.exc_info()
                    exc_lines = traceback.format_exception(exc_type,
                                                           exc_value,
                                                           tb)
                    exc_value.child_traceback = ''.join(exc_lines)

                    # 通過pipe通知父進程錯誤信息
                    os.write(errpipe_write, pickle.dumps(exc_value))

                # 子進程如果出錯, 直接退出. 退出會關閉所有pipe
                os._exit(255)

            # 以下是父進程的流程
        finally:
            # 4) 父進程不需要通知子進程錯誤消息, 直接關閉pipe的寫入端.
            os.close(errpipe_write)

        # 6) 父進程阻塞的讀取子進程發來的錯誤消息.
        data = _eintr_retry_call(os.read, errpipe_read, 1048576)
    finally:
        # 無論成功與否, 父進程不再需要從子進程讀取任何消息了, 關閉pipe的讀取端.
        os.close(errpipe_read)

    if data != "":
        # 父進程的錯誤處理...
    # 8) 9)

我們把上面的代碼的執行過程整理成時間表, 如下:

步驟 時間 動作 echo線程 sleep線程 父進程打開的fd echo子進程的fd sleep子進程的fd
1 0.00 創建通信的pipe 4,5=os.pipe() 6,7=os.pipe() 4,5,6,7 - -
2 0.00 echo線程fork fork - 4,5,6,7 4,5,6,7 -
3 0.00 sleep線程fork - fork 4,5,6,7 4,5,6,7 4,5,6,7
4 0.00 父進程關閉寫pipe close(5) close(7) 4,-,6,- 4,5,6,7 4,5,6,7
5 0.00 子進程關閉讀pipe - - 4,-,6,- -,5,6,7 4,5,-,7
6 0.00 父進程阻塞讀 read(4)… read(6)… 4,-,6,- -,5,6,7 4,5,-,7
7 0.00 子進程exec, 關閉自己的的pipe-fd - - 4,-,6,- -,-,6,7 4,5,-,-
8 0.01 echo子進程結束, sleep線程返回 - read(6):done 4,-,6,- -,-,-,- 4,5,-,-
9 0.03 sleep子進程結束, echo線程返回 read(4):done - 4,-,6,-   -,-,-,-

Popen 調用時創建1對pipe和子進程通信, Popen 返回時, 子進程就已經創建成功, pipe也在子進程exec時關閉了.

但如果同時有2個 Popen 在調用, 父進程中會同時出現2對或幾對pipe.

這幾對pipe會在fork時被繼承到子進程. 子進程在進行exec之前(創建pipe時), 已經將pipe的fd設置FD_CLOEXEC: 執行exec時自動關閉fd. 但并沒有對其他fd進行這個設置 .

因此, 如果并發地調用 Popen , 1個子進程會在fork時帶著為別的子進程準備的pipe fd, 并且不會關閉它們(因為子進程只知道自己的pipe fd, 沒有設置 close_fds 時, 它不會魯莽地關閉其他fd)! 這樣1個pipe fd本應在父子進程這2個進程之間共享, 卻意外地會在3個或更多的進程中處于打開狀態.

而父進程中的Popen在阻塞的read pipe, 自己的子進程exec后自動關閉了這個pipe fd, 進而讓父進程結束read, 但還有另外一個進程在打開著這個pipe fd(步驟7)(我們的例子中是sleep子進程繼承了echo 子進程的pipe fd并且沒有關閉), 父進程中的read不會檢查到fd關閉, 一直保持阻塞讀的狀態.

直到所有繼承了這個pipe fd的進程都退出了, 父進程的read才能結束(sleep子進程退出時, 自動關閉了所有fd, 包括為echo子進程準備的pipe fd, 到此時父進程read才能收到1個EOF并退出read的阻塞).

 

來自:http://drmingdrmer.github.io/tech/programming/2017/11/20/python-concurrent-popen.html

 

 本文由用戶 woshi123 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!