Odd behavior with os.fork and time.sleep

Yin yin_12180 at yahoo.com
Fri Sep 16 12:40:34 EDT 2005


I am writing a script that monitors a child process.  If the child
process dies on its own, then the parent continues on.  If the child
process is still alive after a timeout period, the parent will kill the
child process.  Enclosed is a snippet of the code I have written.  For
some reason, unless I put in two time.sleep(4) commands in the parent,
the process will not sleep.  Am I forgetting something?  Any reasons
for this strange behavior?

Linux Fedora Core 4
Python 2.4.1

Thanks.

#!/usr/bin/env python

import os, time
import signal
import sys

def chldhandler(signum, stackframe):
  while 1:
    try:
      result = os.waitpid(-1, os.WNOHANG)
    except:
      break
    print "Reaped child process %s" % result[0]
  signal.signal(signal.SIGCHLD, chldhandler)

signal.signal(signal.SIGCHLD, chldhandler)

pid = os.fork()
if pid:  # parent
  print "Parent.  Child is %d" % pid

  try:
    os.kill(pid, 0)
    print "Killed child"
    os.kill(pid, signal.SIGKILL)
  except OSError, err:
    print "Child is dead"

  print "In parent again"
  time.sleep(4)
  time.sleep(4)

  print "Parent awake"
else:  # child
  print "Child sleeping 5 seconds..."
  time.sleep(5)
  print "Child awake"




More information about the Python-list mailing list