I want to write a long-running shell script so that only one copy could be run at a time. If the script crashes, I want a new invocation of the script not to be stopped by a lock from the crashed invocation.

Is lockfile-* set of utils the right thing to use? Is there a chance of a race condition while using them in a script?

Does --use-pid lift the 5-minutes limitation mentioned on the man page? My scripts run significantly longer.

I use an Ubuntu 10.10 instance on Amazon EC2; no NFS or something like that.


While creating a lock can be done with the lockfile command or the flock system call or by creating a directory (which is an uninterupptable action) the second part is more tricky.

If the lock exists - how do you determine, if the lock belongs to a still running process?

The most common solution is to put the PID of the process into the lock-file.

Before trying to create a lock you have to check if the lock-file already exists. If so, check if the PID matches a running process that resembles the process that should create the lock. If this is not the case, remove the lock and recreate it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.