【问题标题】:OSError in os.wait in pythonpython中os.wait中的OSError
【发布时间】:2012-04-16 20:53:39
【问题描述】:

您好,我正在尝试在 python 中执行小代码,它给出了操作系统错误。

>>> import os
>>> def child():
...     pid = os.fork()
...     if not pid:
...             for i in range(5):
...                     print i
...     return os.wait()
...
>>> child()
0
1
2
3
4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in child
OSError: [Errno 10] No child processes

我无法弄清楚为什么它会给出 OSError。我用谷歌搜索它,它被记录为 python 2.6 或更早版本的错误。我正在使用python2.7。

【问题讨论】:

  • 你好,这是 ubuntu-server 版本

标签: python operating-system fork


【解决方案1】:

你错过了一个 else。因此,您在子进程中调用os.wait()(他们没有自己的子进程,因此出现错误)。

以下更正代码:

import os
def child():
    pid = os.fork()
    if not pid:
            for i in range(5):
                    print i
    else:
        return os.wait()

child()

【讨论】:

  • 您好,这很有效。但我无法理解错误原因。能详细点吗?
  • 阅读更多关于多进程编程的信息。 (例如:alumni.cs.ucr.edu/~ysong/cs160/lab1/multiprocess.htmlusers.actcom.co.il/~choo/lupg/tutorials/multi-process/…)当你fork时,会创建一个子进程,它与父进程相同。除了一个区别 - fork 函数的返回值。孩子得到 0,父母得到孩子的 PID。但是,当任何进程结束时,它必须将其返回值传递给其父进程。父进程可以使用wait 函数读取它。如果一个进程没有子进程,调用wait是没有意义的,会报错。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-26
  • 2010-10-28
  • 1970-01-01
  • 1970-01-01
  • 2017-07-15
  • 1970-01-01
  • 2014-02-02
相关资源
最近更新 更多