Python fork-exec问题,子进程输出与父进程位于同一位置

发布于 2024-09-11 23:06:52 字数 655 浏览 3 评论 0原文

尝试使用以下代码:python fork.py 和:python fork.py 1 看看它的作用。

#!/usr/bin/env python2

import os
import sys

child_exit_status = 0
if len(sys.argv) > 1:
    child_exit_status = int(sys.argv[1])

pid = os.fork()
if pid == 0:
    print "This is the child"
    if child_exit_status == 0:
        os.execl('/usr/bin/whoami')
    else:
        os._exit(child_exit_status)
else:
    print "This is the parent"
    (child_pid, child_status) = os.wait()
    print "Our child %s exited with status %s" % (child_pid, child_status)

问题:为什么子进程可以执行“打印”并且仍然输出到与父进程相同的位置?

(我在 Ubuntu 10.04 上使用 Python 2.6)

Try the code below with: python fork.py and with: python fork.py 1 to see what it does.

#!/usr/bin/env python2

import os
import sys

child_exit_status = 0
if len(sys.argv) > 1:
    child_exit_status = int(sys.argv[1])

pid = os.fork()
if pid == 0:
    print "This is the child"
    if child_exit_status == 0:
        os.execl('/usr/bin/whoami')
    else:
        os._exit(child_exit_status)
else:
    print "This is the parent"
    (child_pid, child_status) = os.wait()
    print "Our child %s exited with status %s" % (child_pid, child_status)

Question: How come the child process can do 'print' and it still gets outputted to the same place as the parent process?

(Am using Python 2.6 on Ubuntu 10.04)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

哆兒滾 2024-09-18 23:06:52

在linux下,子进程继承(几乎)父进程的所有内容,包括文件描述符。在您的情况下,文件描述符 1 (stdout) 和文件描述符 2 (stderr) 打开与父级相同的文件。

请参阅 fork() 的手册页。

如果您希望子级的输出到其他地方,您可以在子级中打开一个新文件。

Under linux, the child process inherits (almost) everything from the parent, including file descriptors. In your case, file descriptor 1 (stdout) and file descriptor 2 (stderr) are open to the same file as the parent.

See the man page for fork().

If you want the output of the child to go someplace else, you can open a new file(s) in the child.

不打扰别人 2024-09-18 23:06:52

因为您尚未更改子文件描述符 1(标准输出)的目标。

Because you haven't changed the destination of file descriptor 1, standard output, for the child.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文