我目前正在創建一個鎖文件夾,它在我的腳本運行時創建,我也將文件移動到子文件夾中進行處理。腳本結束時會調用一個TRAP,它會刪除鎖定文件夾和內容,所有這些都可以正常工作。有一天我們有一個問題,當有人從一臺服務器上拉下電源時,我的TRAP從來沒有被調用,所以當重新啓動時,鎖定文件夾仍然存在,這意味着我的腳本無法重新啓動,直到它們被手動刪除。檢查腳本是否已在運行的最佳方法是什麼?我當前使用的進程ID的這種做法:創建鎖文件shell
if ! mkdir $LOCK_DIR 2>/dev/null; then # Try to create the lock dir. This should pass successfully first run.
# If the lock dir exists
pid=$(cat $LOCK_DIR/pid.txt)
if [[ $(ps -ef | awk '{print $2}' | grep $pid | grep -v grep | wc -l) == 1 ]]; then
echo "Script is already running"
exit 1
else
echo "It looks like the previous script was killed. Restarting process."
# Do some cleanup here before removing dir and re-starting process.
fi
fi
# Create a file in the lock dir containing the pid. Echo the current process id into the file.
touch $LOCK_DIR/pid.txt
echo $$ > $LOCK_DIR/pid.txt
# Rest of script below
檢查'man 1 lockfile lockfile-check lockfile -create lockfile-remove lockfile-touch' – anishsane
使用'flock'命令。 'man flock'包含示例 – hek2mgl
根據我的理解,使用mkdir也是一個原子操作,因爲我需要該目錄的每個運行,所以它可能被用作主鎖「文件」。我不確定我會如何與當前的實施聯繫起來? –