Command/tool to prevent running an app more than once

There's a simple utility called flock that will wrap a process in a lockfile and by default creates an exclusive lock. This means that subsequent runs of the process wrapped by the flock file will fail if the previous invocation is still running.

You can also tell flock to fail immediately instead of wait for the lock:

flock -xn /bin/yourcmd

This binary is a part of the util-linux package which should be available by default on your distro of choice.


You can do this with a lockfile routine (usually a directory) in your script... PID is the right way to handle this, but the lock file could be a quick way of achieving what you want. Also see this StackOverflow solution.

An example with explanation from a Perl script I use often. It can only have one instance running at a time:

# Set two variables that are used by the code that ensures that only
# one Orca process is using a particular configuration file at a
# particular time.  This is done by using the fact that mkdir() is
# atomic.  The first variable is the name of the directory to create
# and the second is a flag used by the Orca clean up code to see if
# the locking directory should be removed.
my $locking_directory       = "$config_filename.lock";
my $rmdir_locking_directory = '';

# Install signal handlers to clean Orca up, including the locking
# directory.
$SIG{INT}     = \&catch_signal;
$SIG{PIPE}    = \&catch_signal;
$SIG{TERM}    = \&catch_signal;
$SIG{__DIE__} = \&catch_die;

# Now try to create the locking directory.
unless (mkdir($locking_directory, 0755)) {
  die "$0: cannot create locking directory '$locking_directory': $!\n";
}
$rmdir_locking_directory = 1;

Nothing else comes to mind.

However, what you are wanting is a script you could easily write. The requirements would be (not in programmatic order):

  • Start the process and store the PID in some way that uniquely identifies the program being run
  • Check that if there is a PID file, the PID in it corresponds to an existing instance of that program; if it does, abort; if it doesn't, start the process as normal and replace the PID file
  • Return your status

This is much of the functionality of start-stop-daemon, so it does lead one to wonder why you don't simply ignore the functionality in that which you don't need, and use it. You could even make a script or an alias to wrap it so that you could type a very small amount of characters.

For the sake of interest, you can also do this without PID files and catch all processes running with a particular filename (not pathname) whether started "properly" or not, by using pidof in your script.