1

This is a shell script with a function timeout() to limit the CPU time usage for a single process. Is it possible to limit memory usage for a single Linux process with a similar function?

#!/bin/bash

################################################################################
# Executes command with a timeout
# Params:
#   $1 timeout in seconds
#   $2 command
# Returns 1 if timed out 0 otherwise
timeout() {

    time=$1

    # start the command in a subshell to avoid problem with pipes
    # (spawn accepts one command)
    command="/bin/sh -c \"$2\""

    expect -c "set echo \"-noecho\"; set timeout $time; spawn -noecho $command; expect timeout { exit 1 } eof { exit 0 }"

    if [ $? = 1 ] ; then
        echo "Timeout after ${time} seconds"
    fi
}


timeout 100 "./program.exe"

done
exit 0

I've read a similar question Limit memory usage for a single Linux process, all the answers below rely on extra tools or configurations. I tried some but failed (for example, the accepted answer https://unix.stackexchange.com/a/44988/302092 recommends a tool, but I got an unexpected output when I run the example given by its Github page).

ulimit works but the I needs reset the ulimit to unlimited after the last process done. So I wonder is there any easier way (maybe with only a function) to achieve this currently?

sirius
  • 111
  • 5

0 Answers0