this repo has no description
1#!/bin/bash
2# time-and-mem-limit
3# Ralph Becket <rafe@csse.unimelb.edu.au>
4# Tue Feb 10 12:21:58 EST 2009
5#
6# usage: time-and-mem-limit N M cmd ...
7#
8# Kill cmd ... if it does not terminate after N seconds of wallclock time or if
9# it uses more than M megabytes of memory. Either "EXCEEDED TIME LIMIT" or
10# "EXCEEDED MEMORY LIMIT" is printed on stderr as appropriate if cmd ... is
11# killed for one of these reasons.
12
13USAGE="usage: time-and-mem-limit num-seconds num-megabytes cmd ..."
14
15if [ "$*" = "-h" -o "$*" = "--help" ]
16then
17 echo $USAGE >&2
18 exit 0
19fi
20
21if [ $# -lt 3 ]
22then
23 echo $USAGE >&2
24 exit 1
25fi
26
27# CMDPID: we exec the command so it gets the current PID.
28CMDPID=$$
29# TIMELIMIT: the time limit in seconds.
30TIMELIMIT=$1
31# MEMLIMIT: the memory limit in megabytes.
32MEMLIMITMB=$2
33MEMLIMITKB=$(($MEMLIMITMB << 10))
34shift 2
35# CMD: anything else on the command line is the command to be executed.
36CMD=$@
37
38declare TimeoutOrig=$(ulimit -t)
39declare MemoryOrig=$(ulimit -v)
40
41# Using ulimit like this doesn't work on Cygwin.
42#
43if test ! -e /bin/cygpath.exe
44then
45 ulimit -S -t ${TIMELIMIT}
46 ulimit -S -v ${MEMLIMITKB}
47else ### Only on Cygwin: Ubuntu 15 does not allow to delete output files and reports wrong exit result
48 # Check the time and memory limits every ten seconds in a background
49 # process. If either limit is reached, kill the process.
50 (
51 for (( i=0 ; i<$TIMELIMIT ; i+=1 ))
52 do
53 # Sleep for 1 seconds.
54 sleep 1
55 # Obtain the process memory usage in kilobytes.
56 # (We use this form of ps arguments for portability).
57 CMDMEMUSAGEKB=`ps -p $CMDPID -o vsize=""`
58 # Quit if the process has already terminated.
59 if [ -z $CMDMEMUSAGEKB ]
60 then
61 exit 0
62 fi
63 # Kill the process if it has exceeded its memory limit.
64 if [ $CMDMEMUSAGEKB -gt $MEMLIMITKB ]
65 then
66 kill -KILL $CMDPID >/dev/null 2>&1
67 echo "" >&2
68 echo "EXCEEDED MEMORY LIMIT OF $MEMLIMITMB Mbytes" >&2
69 exit 1
70 fi
71 done
72 # Kill the process if it has exceeded its time limit.
73 if ps -p $CMDPID >/dev/null 2>&1
74 then
75 kill -KILL $CMDPID >/dev/null 2>&1
76 echo "" >&2
77 echo "EXCEEDED TIME LIMIT OF $TIMELIMIT s" >&2
78 exit 1
79 fi
80 ) &
81
82 # The background process above sometimes does not seem to fire or does not
83 # kill all subprocesses. "ulimit" is more reliable, but it is not clear how
84 # to get useful, specific error messages. Thus for now we use both methods.
85fi
86
87# Run the command.
88exec $CMD
89
90if test ! -e /bin/cygpath.exe
91then
92 ulimit -S -t ${TimeoutOrig}
93 ulimit -S -v ${MemoryOrig}
94fi