limit-process.sh

#!/bin/bash

# -a     All current limits are reported
# -b     The maximum socket buffer size
# -c     The maximum size of core files created
# -d     The maximum size of a process's data segment
# -e     The maximum scheduling priority ("nice")
# -f     The maximum size of files written by the shell and its children
# -i     The maximum number of pending signals
# -l     The maximum size that may be locked into memory
# -m     The maximum resident set size (many systems do not honor this limit)
# -n     The maximum number of open file descriptors (most systems do not allow this value to be set)
# -p     The pipe size in 512-byte blocks (this may not be set)
# -q     The maximum number of bytes in POSIX message queues
# -r     The maximum real-time scheduling priority
# -s     The maximum stack size
# -t     The maximum amount of cpu time in seconds
# -u     The maximum number of processes available to a single user
# -v     The maximum amount of virtual memory available to the shell
# -x     The maximum number of file locks
# -T     The maximum number of threads

ulimit -v 50000;
ulimit -u 20;

if [ -n "$1" ]; then

    # start the appplication given as argument, with
    # - lower CPU priority
    # - max memory limit
    # - max process limit

    renice -n 15 $$;
    exec $@;

else

    # test the ulimit setting with perl

    # memory
    if perl -le'$s = "x" x 10_000_000' 2>/dev/null; then
        echo "ok - perl with 10M of memory";
    else
        echo "not ok - perl with 10M of memory";
    fi

    if perl -le'$s = "x" x 30_000_000' 2>/dev/null; then
        echo "ok - perl with 30M of memory";
    else
        echo "not ok - perl with 30M of memory";
    fi

    # processes
    if perl -le'for(1..5) { next if fork; last if $!; sleep 1; last } wait; exit $!'; then
        echo "ok - perl with 5 children";
    else
        echo "not ok - perl with 5 children";
    fi

    if perl -le'for(1..20) { next if fork; last if $!; sleep 1; last } wait; exit $!'; then
        echo "ok - perl with 20 children";
    else
        echo "not ok - perl with 20 children";
    fi

fi