Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regarding The os.fork() Function In Python

Tags:

python

fork

I'm just beginning with python and I developed a simple program to fork a parent process. Here's the code I've written so far...

#!/usr/bin/env python
import os

def child():
    print "We are in the child process with PID= %d"%os.getpid()

def parent():
    print "We are in the parent process with PID= %d"%os.getpid()
    newRef=os.fork()
    if newRef==0:
        child()
    else:
        print "We are in the parent process and our child process has PID= %d"%newRef

parent()

From what I understand, the code should begin by calling the parent process and display its PID. Afterwards, the os.fork() is called and it creates a copy of the parent process, and since we are already in the parent process, the newRef variable should contain a value that is positive and the else part of my code is the one that should be executed. My question is that: why did the code initiate to call the child() function afterwards although the if part of my code should not execute.

Thanks in advance :)

like image 832
user3490561 Avatar asked Jul 02 '14 18:07

user3490561


2 Answers

After you return from fork, you now have two processes executing the code immediately following fork.

So your statement:

since we are already in the parent process

is only half-true. After os.fork returns, the parent process continues executing the code as the parent process, but the child process continues executing the exact same code with the same local and global variables, with the exception of the return value of fork. So, from the child process's perspective, newRef has the value of 0, and from the parent's perspective, newRef has a positive value. Both processes will execute the code accordingly.

like image 146
Chris Barker Avatar answered Sep 17 '22 13:09

Chris Barker


When you call os.fork, you create a new process that is an exact copy of the existing process except that in the original process, fork returns the process ID of the new (child) process, and in the new process, fork returns 0. This difference is how you can do something different in the parent and in the child.

In your specific code, the return value of fork in the child is 0, so the child process calls the child function. In the parent, the return value is not 0, so the else clause is executed.

like image 27
murgatroid99 Avatar answered Sep 21 '22 13:09

murgatroid99