6

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

1
  • 2
    These are an absolute bear to trace when they get more complicated. The one thing to remember is that when you call that fork() function, it creates an EXACT in-memory duplicate of the current process at that EXACT point. try running if fork() != fork(): fork() Commented Jul 2, 2014 at 18:35

2 Answers 2

17

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.

Sign up to request clarification or add additional context in comments.

Comments

7

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.