Python fork-exec问题,子进程输出与父进程位于同一位置
尝试使用以下代码: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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在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.
因为您尚未更改子文件描述符 1(标准输出)的目标。
Because you haven't changed the destination of file descriptor 1, standard output, for the child.