Jump to content

User:CCChen

From Wikipedia, the free encyclopedia
[edit]

--- {{{

  1. !/usr/bin/env python

import os import time

def compute(w):

   print "computing..."
   time.sleep(10)
   os.write(w, "8")
   os._exit(0)

def process(job, timeout):

   (r, w) = os.pipe()
   pid = os.fork()
   jobdone = 0
   if pid: ##parent
       #os.kill(pid, 9)
       start = time.time()
       while not jobdone:
           now = time.time()
           print now
           if (now - start) >= timeout:
               print "killing process " + str(pid)
               os.kill(pid, 9)
               jobdone = 1
               return timeout
           stat = os.waitpid(pid, os.WNOHANG)
           #print "stat=" + str(stat)
           if stat == (0, 0):
               #print "child not completed!"
               time.sleep(1)
           else:
               print "child completed!"
               jobdone = 1
               return os.read(r, 10)
       #os.kill(pid, 9)
       #print "this is parent"
   else:
       job(w)


def dummy():

   pid = os.fork()
   if pid: ##parent
       stat = os.waitpid(pid, os.WNOHANG)
       if stat == (0, 0):
           print "child not completed!"
       else:
           print "child completed!"
       print stat
       os.kill(pid, 9)
       print "this is parent"
   else:
       time.sleep(1)
       print "I'm child"

if __name__ == "__main__":

   result = process(compute, 4)
   print "result=" + str(result)

}}}