python subprocess.Popen 在激活线程后抛出错误

python subprocess.Popen throwing error while after a Thread is activated

我环顾四周,但没有看到关于这个特定问题的任何信息,所以我想我应该在这里问一下:

每当我在启动随机线程后尝试 运行 调用 subprocess.Popen 时,我都会收到 OSError。我的假设是 subprocess.py 与多线程相关的某些方面我不理解。

我在 QNX 系统上 运行ning python 2.7.3。

代码测试:

import subprocess
import time
from threading import Thread

def Test():
  while(1):
     print "Testing."
     time.sleep(1)

if __name__=="__main__":
   subprocess.Popen('ls') # runs just fine

   Thread(target=Test).start()

   subprocess.Popen('ls') # throws OSError

回溯

Traceback (most recent call last):
   File "test.py", line 16 in <module>
      subprocess.Popen('ls')
   File "usr/local/lib/python2.7/subprocess.py", line 679, in __init__
      errread, errwrite)
   File "usr/local/lib/python2.7/subprocess.py", line 1143, in _execute_child
      self.pid = os.fork()
OSError: [Errno 89] Function not implemented

QNX 的设计目的不是在进程已经生成新线程后支持进程内的 fork()。来自 QNX 文档...

Suppose you have a process and you haven't created any threads yet (i.e., you're running with one thread, the one that called main()). When you call fork(), another process is created, also with one thread. This is the simple case.

Now suppose that in your process, you've called pthread_create() to create another thread. When you call fork(), it will now return ENOSYS (meaning that the function is not supported)! Why?

Well, believe it or not, this is POSIX compatible — POSIX says that fork() can return ENOSYS. What actually happens is this: the Neutrino C library isn't currently built to handle the forking of a process with threads. When you call pthread_create(), the function sets a flag, effectively saying, “Don't let this process fork(), because I'm not prepared to handle it.” Then, in the library fork() function, this flag is checked, and, if set, causes fork() to return ENOSYS.

(source,阅读 Process creation and threads 部分。)

我假设 Thread(target=Test).start() 调用 pthread_create() 并解释了您看到的错误。

另外值得注意的是ENOSYS的定义也指定了函数没有实现。请参阅以下定义...

ENOSYS Function not implemented (POSIX.1-2001).

(source)

因此,这是一个 OS 级别的约束。 Python 不是问题!