Search This Blog

Monday, September 28, 2015

fork Demo - Python

[dvaidyula@qa-test temp]$ cat fork_demo.py
import os

def parent_process():
    print "I am the parent process with pid %s" %os.getpid()
    childId = os.fork()
    print "I am in the parent loop still and pid is %s" %os.getpid()
    print "ChildID is %s" %childId

    if childId ==  0 :
        child_process()
    else:
        print "We are inside child process and pid is %s" %childId

def child_process():
    print "I am the child process and pid is %s" %os.getpid()
    print "The child is exiting"

parent_process()
[dvaidyula@qa-test temp]$
[dvaidyula@qa-test temp]$ py fork_demo.py
I am the parent process with pid 5317
I am in the parent loop still and pid is 5318
ChildID is 0
I am the child process and pid is 5318
The child is exiting
I am in the parent loop still and pid is 5317
ChildID is 5318
We are inside child process and pid is 5318

### EXECVP ####
[dvaidyula@qa-test temp]$ python
Python 2.6.6 (r266:84292, Jan  2 2013, 10:42:24)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>>
>>> 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_seq=1 ttl=64 time=0.023 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.007 ms
64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.005 ms

--- 127.0.0.1 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2000ms
rtt min/avg/max/mdev = 0.005/0.011/0.023/0.009 ms

[dvaidyula@qa-test temp]$  # Note that once we kill, it is exiting the python prompt / parent process


No comments:

Post a Comment