May someone explain the following os.fork() example to me?

parallel-processing, python

Solution

1: How come the value of os.getpid() is never changed when the code runs?

The value of `os.getpid()` will never change for the parent since that's always the same process. The pid will change every time for the child since `fork()` always creates a brand new child process clone with its own PID.

2: Why is the child() function ever called? Let's say that the value of newpid != 0, then the program will print out print('Hello from parent', os.getpid(), newpid). However, after that, it prints the line from child rather than asking for an input as the case is after the if statement.

The child process is called because there are now two processes running. One called the `child()` function, the other called the `print` function. They are simply fighting for printing to the screen, and you saw the parent print "win" first in this case.

3: What is os._exit(0) doing?

See here: https://docs.python.org/2/library/os.html#os._exit

Exit the process with status n, without calling cleanup handlers, flushing stdio buffers, etc.

Problem

[Code taken from Programming 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 the code outputs when ran: ``` 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()` is used to start another process in parallel to the current one. - `os.fork()` creates a copy of the previous Python session and opens it in parallel. - `os.fork()` returns the id of the new process. Things I don't understand: - How come the value of `os.getpid()` is never changed when the code runs? - Why is the `child()` function ever called? Let's say that the value of `newpid` != 0, then the program will print out `print('Hello from parent', os.getpid(), newpid)`. However, after that, it prints the line from child rather than asking for an input as the case is after the if statement. - What is `os._exit(0)` doing? Thanks a ton for your time. :)

Original source