import os, signal, time def execute(): for i in range(30): print("Counter = {}, going to sleep for 1 second".format(i)) time.sleep(1) def _alarm(signum, frame): os.kill(pid, signal.SIGTERM) # Kill our child print("Terminated forked job") os._exit(1) def handleexecution(): global pid uname() # Fork the process; the child will do the work; the parent will monitor the maximum runtime pid = os.fork() if pid: # We are the parent process # set a signal to kill the child process after the maximum runtime signal.signal(signal.SIGALRM, _alarm) signal.alarm(120) os.wait() # Wait for the child process to terminate return # Exit normally execute() os._exit(0) def uname(): print(os.popen("uname").read()) if __name__ == "__main__": handleexecution()