开发者

Python fork-exec problem, child process output goes to same place as parent process

开发者 https://www.devze.com 2023-01-09 18:14 出处:网络
Try the code below with: python fork.py and with: python fork.py 1 to see what it does. #!/usr/bin/env python2

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' an开发者_开发技巧d it still gets outputted to the same place as the parent process?

(Am using Python 2.6 on Ubuntu 10.04)


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消