[Code taken from Python 4th Edition by Mark Lutz]
"forks child processes until you type 'q'" import os def child(): print('Hello from child', os.getpid()) os._exit(0) # else goes back to parent loop def parent(): while True: newpid = os.fork() if newpid == 0: child() else: print('Hello from parent', os.getpid(), newpid) if input() == 'q': break parent()
What code displays at startup:
Hello from parent 2057 2062 Hello from child 2062 Hello from parent 2057 2068 Hello from child 2068 Hello from parent 2057 2069 Hello from child 2069 Hello from parent 2057 2070 Hello from child 2070 q
Things I understand:
os.fork() used to start another process in parallel with the current one.os.fork() creates a copy of the previous Python session and opens it in parallel.os.fork() returns the identifier of the new process.
Things I don't understand:
- Why
os.getpid() value never change when the code runs? - Why has the
child() function ever been called? Say that the value of newpid ! = 0, then the program prints print('Hello from parent', os.getpid(), newpid) . However, after that, it prints a line from the child, and does not ask for input, since this happens after the if statement. - What does
os._exit(0) do?
Thank you a ton for your time. :)
python parallel-processing
Always learning forever
source share