天天看點

使用Popen運作程式逾時就kill

使用Popen運作gcc生成的小程式,逾時後就殺掉

使用字元串作為小程式的輸入,并傳回輸出.

def popenKillTimeout(popenargs, stdinStr='', timeOut=1, **kwargs):
    process = sp.Popen(popenargs, stdin=sp.PIPE, stdout=sp.PIPE,
                       stderr=sp.PIPE, preexec_fn=os.setsid, **kwargs)
    process.stdin.write(stdinStr + '\n')
    timeUnit = 0.001
    timeStepNum = int(1 / timeUnit * timeOut)
    for i in xrange(timeStepNum):
        time.sleep(timeUnit)
        if process.poll() is None:
            if i == (timeStepNum - 1):
                print 'kill ' + str(process.pid)
                os.killpg(process.pid, sp.signal.SIGUSR1)
                return -1, '#!timeout!#', 'timeout'
            else:
                continue
        else:
            break
    output, err = process.communicate()
    return process.poll(), output, err