Limit number of program executions

executablelimit

Please help me to find out how to limit number of program concurrent executions. I mean, particular program can be ran only, for example 5 times at once. I know how to limit proccess number for user, but how to do that for program, using PAM?

Best Answer

PAM is used to authorize logins and account modifications. It is not at all relevant to restricting a specific program.

The only way to apply a limit to the number of times a program can be executed is to invoke it through a wrapper that applies this limit. Users can of course bypass this wrapper by having their own copy of the program; if you don't want that, don't give those users account on your machine.

To restrict a program to a single instance, you can make it take an exclusive lock on a file. There's no straightforward way to use a file to allow a limited number of instances, but you can use 5 files to allow 5 instances, and make the wrapper script try each file in turn. Create a directory /var/lib/myapp/instances (or wherever you want to put it) and create 5 files in it, all world-readable but only writable by root.

umask 022
mkdir /var/lib/myapp
touch /var/lib/myapp/instances/{1,2,3,4,5}

Wrapper script (replace myapp.original by the path to the original executable), using Linux's flock utility:

#!/bin/sh
for instance in /var/lib/myapp/instances/*; do
  flock -w 0 -E 128 "$instance" myapp.original "$@"
  ret=$?
  if [ "$ret" -ne 128 ]; then exit "$ret"; fi
done
echo >&2 "Maximum number of instances of myapp reached."
exit 128
Related Question