3 ms·
While I find the "almost hilarious" kind of overly snarky, I have my own version of this that has the race condition check. Basically uses `mkdir $THISBIN.lock
by michaelcampbell 6y ago
While I find the "almost hilarious" kind of overly snarky, I have my own version of this that has the race condition check. Basically uses `mkdir $THISBIN.lock` line that gives me an atomic way to create or check for existence of a logical semaphore, and provides me with a scratch area. The trap'd cleanup function removes it (which when debugging, and I use that scratch area, is inconvenient, but <shrug>)
- twic 6y agoRead to the end before screaming. I do this: exec >>$log_file 2>&1 if ! flock --exclusive --nonblock 1 then log "unable to get exclusive lock, aborting" exit 1 fi Which redirects standard output to a log file, then tries to get an exclusive lock on it. The lock is created by the flock subprocess, but continues to exist until the script exits and closes that file descriptor. This means there can only be one process writing to a given log file at a time. For me, that is the right granularity of locking - i have several cron jobs running this script, but with different arguments, and writing to different log files.
- AdamGibbins 6y agoflock isn't all platforms unfortunately, doesn't exist on MacOS.
- twic 6y agoQuite true. On OS X, this script will do the right thing and not run until you get a proper computer.
- michaelcampbell 6y agoI like the idea of a separate lock/semaphor per input args. Haven't needed that yet but I can see where I might.
- mradzikowski 6y agoWell, I agree with your cron argument. On the other hand - sometimes I have some utility scripts, for example to trigger some processing, that I want to run multiple times at the same time, with different arguments. So lock is not a universal thing for me. (I'm the article author btw)
- michaelcampbell 6y agoSure; my template is a one-size-fits-all thing, so if I know I'm not worried about race conditions for a file I just remove that bit.