Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python checking if a fork() process is finished

Tags:

python

fork

Just wondering if some one could help me out. The problem I'm having is that I os.fork() to get several bits of information and send them to a file, but checking to see if the fork process is not working.

import sys
import time
import os
import re


ADDRESS  = argv[1]
sendBytes = argv[2]


proID2 = os.fork()
if proID2 == 0:
    os.system('ping -c 20 ' + ADDRESS + ' > testStuff2.txt')
    os._exit(0)

print proID2

finn = True
while finn == True:
time.sleep(1)
finn = os.path.exists("/proc/" + str(proID2))
print os.path.exists("/proc/" + str(proID2))
print 'eeup out of it ' + str(proID2)

I think that the os.path.exists() is maybe not the right thing to use.

Thanks.

like image 347
Paddy Avatar asked May 21 '12 11:05

Paddy


2 Answers

To wait for the child process to terminate, use one of the os.waitXXX() functions, such as os.waitpid(). This method is reliable; as a bonus, it will give you the status information.

like image 111
NPE Avatar answered Oct 25 '22 19:10

NPE


While you can use os.fork() and os.wait() (see below for an example), you are probably better off using methods from the subprocess module.

import os, sys

child_pid = os.fork()
if child_pid == 0:
    # child process
    os.system('ping -c 20 www.google.com >/tmp/ping.out')
    sys.exit(0)

print "In the parent, child pid is %d" % child_pid
#pid, status = os.wait()
pid, status = os.waitpid(child_pid, 0)
print "wait returned, pid = %d, status = %d" % (pid, status)
like image 31
mhawke Avatar answered Oct 25 '22 19:10

mhawke