Reputation: 10922
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)
Upvotes: 0
Views: 1955
Reputation: 31176
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.
Upvotes: 3
Reputation: 798456
Because you haven't changed the destination of file descriptor 1, standard output, for the child.
Upvotes: 0