Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question
2  
BashFAQ 45 recommends flock. –  jw013 Aug 27 '12 at 20:18
5  
Duplicate of stackoverflow.com/q/185451/1072112 –  ghoti Aug 27 '12 at 20:30

1 Answer 1

up vote 5 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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