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

[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. :)

+8
python parallel-processing
source share
2 answers

1: Why does the value of os.getpid () never change when the code runs?

The value of os.getpid() will never change for the parent, as it is always the same process. The pid will change each time for the child, since fork() always creates a clone of the new child process with its own PID.

2: 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.

A child process is called because two processes are currently running. One is called the child() function, the other is called the print function. They simply struggle to print on the screen, and in this case you saw the parent print β€œwin”.

3: What does os._exit (0) do?

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

Quit a process with status n without calling cleanup handlers, flushing stdio buffers, etc.

+5
source share
  • Since your parent process always has the same pid if it works ( while True: .
  • The child is actually a copy of the parent. What os.fork does! And the function returns the pid of the child to the parent. So the parent starts the second part of the if else -statement, and all the children start the first part, because os.fork for the child processes returns 0.
  • os._exit is essentially a stripped-down version of os.exit() and is intended for child processes.
+2
source share

All Articles