[ale] Only one process

JK jknapka at kneuro.net
Fri Jun 4 20:49:17 EDT 2010


Doesn't anybody worry about race conditions any more?  How do you
defend against multiple copies of this script running simultaneously?
Of course, cron *shouldn't* ever do that...

flock(1) seems relevant:

http://linux.die.net/man/1/flock

-- JK


On 6/4/2010 11:52 AM, James Sumners wrote:
> This is a situation where I typically take advantage of screen. If you
> tell screen to execute a process, then screen will exit when said
> process quits. For example, `screen bash false` results in screen
> starting and quitting immediately. Therefore, you can do the
> following:
>
> ===== Begin script =====
> #!/bin/bash
>
> SESSION_NAME="myapp"
>
> screen -list | grep ${SESSION_NAME}>  /dev/null
> case $? in
>      [0]*)
>          # screen is already running
>          exit 1;;
>      [1]*)
>          # need to run this thing
>          screen -dmS ${SESSION_NAME} bash -c /path/to/myapp
>          ;;
> esac
> ===== End Script =====
>
> Then you can set a cron job to run this thing every once in a while.
>
> On Fri, Jun 4, 2010 at 1:11 PM, Chris Fowler
> <cfowler at outpostsentinel.com>  wrote:
>> I've been thinking of ways to guarantee that there is only one process
>> of a script running.
>>
>> pid file
>>
>> process looks for pid file.  If it sees one it validates that there
>> truly is a process at the pid.  If not, it creates new pid file and
>> runs.  If so, it sends out error message and exits.
>>
>> The script is in perl so the what this would work is?
>>
>> if(-f $pid_file) {
>>         # Get the pid info
>>         my $pid = `cat $pid_file`;chomp $pid;
>>
>>         # look for process running
>>         if(-f "/proc/$pid/cmdline") {
>>           # We may want to look at cmdline and validate it is really
>>           # this script and not just a reused pid #
>>           die "Process running at $pid already!\n";
>>         } else {
>>           unlink "$pid_file";
>>         }
>>
>> }
>>
>> # Ready to go!
>>
>>
>> I'm just looking for what would be considered "The Right Way(tm)"
>>
>> Chris
>
>


-- 
Forget Jesus: stars died so that you could be here today.
  - physicist Lawrence Krauss


More information about the Ale mailing list