Wednesday, January 23, 2013

Python Fundamentals (Forking)

Forking is cloning a process (child of a process).

"The system function called fork() creates a copy of the process, which has called it. This copy runs as a child process of the calling process. The child process gets the data and the code of the parent process. The child process receives a process number (PID, Process IDentifier) of its own from the operating system. The child process runs as an independant instance, i.e. independent of the parent process. With the return value of fork() we can decide in which process we are: 0 means that we are in the child process while a positive return value means, that we are in the parent process. A negative return value means that an error occurred while trying to fork." (reference: http://www.python-course.eu/forking.php)

import os

def child():
   print 'A new child ',  os.getpid( )
   os._exit(0) # is used for child processes instead of os.exit(0)

def parent():
   while True:
      newpid = os.fork()
      if newpid == 0:
         child()
      else:
         pids = (os.getpid(), newpid)
         print "parent: %d, child: %d" % pids
      if raw_input( ) == 'q': break # will create new child process until 'q + <return>' is inputted.

parent()

No comments:

Post a Comment