3. Forking
Long before biologists started their research of cloning, computer
scientists had a successful history of cloning. They cloned processes,
though they didn't call it cloning but forking.
Cloning of a process
Forking creates an identical process as the parent
The thread of execution is duplicated exactly
at the point of call to fork()
returns 0 in the child
returns pid of child in the parent
PID is differnet for parent / child
4. $ vim create_process.py
#!/usr/bin/env python
import os
def child():
print 'I am the child process and my PID is : %d' % os.getpid()
print 'The child is exiting'
def parent_process():
print 'I am the parent process with PID : %d' % os.getpid()
childpid = os.fork() #os.fork creates new process
#os.fork inside parent process returns pid of child
#and inside child process returns 0
if childpid == 0:
#We are inside the child
child()
else:
#we are inside the parent process
print 'We are inside the parent process'
print 'our child has the PID : %d' % childpid
while True:
pass
parent_process()
5. $chmod a+x create_process.py
$./create_process.py
I am the parent process with PID : 25108
We are inside the parent process
our child has the PID : 25109
I am the child process and my PID is : 25109
The child is exiting
KeyboardInterrupt
^C
6. Use of fork()
Dedicate child to a task given by the parent
Parent and child can communicate if required using IPC
Parent / child binary remains the same
7. Spawning New Processes
os.exec* functions
os.execl
os.execle
…
We use os.execvp(file,args)
Overlays parent process with the child
8. >>> import os
>>> os.execvp('ping',['ping','127.0.0.1'])
PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_req=1 ttl=64 time=0.030 ms
64 bytes from 127.0.0.1: icmp_req=2 ttl=64 time=0.052 ms
64 bytes from 127.0.0.1: icmp_req=3 ttl=64 time=0.057 ms
64 bytes from 127.0.0.1: icmp_req=4 ttl=64 time=0.065 ms
64 bytes from 127.0.0.1: icmp_req=5 ttl=64 time=0.066 ms
^C
--- 127.0.0.1 ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 3997ms
rtt min/avg/max/mdev = 0.030/0.054/0.066/0.013 ms
$
9. This work is licensed under the Creative Commons
Attribution-NoDerivs 3.0 Unported License.
To view a copy of this license, visit http://creativecommons.org/licenses/by-nd/3.0/
Copyright 2013 Mohammad reza Kamalifard.
All rights reserved.