bash flock: exit if can't acquire lock

后端 未结 2 1457
孤街浪徒
孤街浪徒 2020-12-09 04:26

The following lock mechanism is used for preventing a cron job from running concurrently:

#!/bin/bash

echo \"Before critical section\"
(
    fl         


        
2条回答
  •  被撕碎了的回忆
    2020-12-09 04:49

    We use exclusive lock on the script file itself, $0 is the name of command file.

    exec 200<$0
    flock -n 200 || exit 1
    

    The whole solution is in two lines of code. But the trick is to open $0 for reading and then obtain exclusive lock for it.

提交回复
热议问题