I am using cron to run a bash script periodically, and trying to use flock to prevent this script and the processes it creates from being run multiple times.
The entry in crontab to run it every minute is:
*/1 * * * * flock -n /tmp/mylockfile /home/user/myscript.sh arg1 arg2
The problem is, myscript.sh spawns multiple screen sessions in detached mode, it contains
for i in {1..3};
do
screen -d -m ./mysubscript.sh arg3
done
Running screen with "-d -m" as above starts screen in "detached" mode as forked process, but these processes do not inherit the lock from flock, so that every minute 3 new screen processes running mysubscript.sh show up.
If I use "-D -m" instead then only one screen process runs all the time until mysubscript.sh finishes, not three.
What I need is flock to only run myscript.sh if none of the the screen processes running mysubscript.sh are running.
How can this be achieved? Are there flags in screen or flock that can help to achieve this?
EDIT: If I change the line inside the for loop into running mysubscript.sh as a background process with:
./mysubscript.sh arg3 &
The locking behavior is exactly as I want, except that I do not have the separate screens anymore.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…