File: timeout-run.py

package info (click to toggle)
roc-toolkit 0.4.0%2Bdfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 9,684 kB
  • sloc: cpp: 102,987; ansic: 8,959; python: 6,125; sh: 942; makefile: 16; javascript: 9
file content (37 lines) | stat: -rw-r--r-- 687 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from __future__ import print_function

import sys
import os
import threading
import subprocess

try:
    timeout = int(sys.argv[1])
    cmd = sys.argv[2:]
    if len(cmd) == 0:
        raise ValueError()
except:
   print("usage: timeout-run.py TIMEOUT COMMAND...", file=sys.stderr)
   exit(1)

proc = subprocess.Popen(cmd)

def trap():
    print("timeout of {}s expired, aborting".format(timeout), file=sys.stderr)
    try:
        proc.terminate()
    except:
        pass

timer = threading.Timer(timeout, trap)
timer.start()

try:
    ret = proc.wait()
    if ret >= 0:
        os._exit(ret)
    else:
        os.kill(os.getpid(), -ret)
except:
    proc.terminate()
    os._exit(127)