#!/usr/bin/python2.4

# -*- coding: utf-8 -*-


import subprocess
import signal
import time
import os


def sigchld_hnd(signal, frame):
	# do nothing, only needed to wake up time.sleep
	return

def runWithTimeout(cmd, timeout=5):
	# install our own signal handler. otherwise SIG_CHLD is ignored and won't 
	# interrupt time.sleep()
	hnd = signal.signal(signal.SIGCHLD, sigchld_hnd)

	# launch command (the first param needs to be an array of cmd and parameter, this is
 	#                 just a quick hack)
	rpid = subprocess.Popen(cmd.split(" ")).pid

	# wait timeout secs, will be interrupted by SIG_CHLD
	time.sleep(timeout)

	# did the child finish already?
	(pid, stat) = os.waitpid(rpid, os.WNOHANG)
	
	if (pid != rpid) or (pid == rpid and (not os.WIFEXITED(stat))):
		# child did not finish yet
		# send SIGKILL to child
		os.kill(rpid, signal.SIGKILL)
		# remove defunct pcb
		(pid, stat) = os.waitpid(rpid, 0)

	# restore old signal handler (in case you need it elsewhere)
	signal.signal(signal.SIGCHLD, hnd)
	


cmd="sleep 1"
runWithTimeout(cmd)
