bash - Creating lock files shell -


i'm creating lock folder created when script runs, move files sub folders here processing. when script ends trap called removes lock folder , contents, of working fine. had issue other day when pulled power 1 of servers trap never called when re-booted lock folder still there meant scripts couldn't re-start until manually removed. what's best way of checking if script running ? have approach using process id's:

if ! mkdir $lock_dir 2>/dev/null;  # try create lock dir. should pass first run.     # if lock dir exists     pid=$(cat $lock_dir/pid.txt)     if [[ $(ps -ef | awk '{print $2}' | grep $pid | grep -v grep | wc -l) == 1 ]];          echo "script running"          exit 1     else         echo "it looks previous script killed. restarting process."          # cleanup here before removing dir , re-starting process.       fi fi  # create file in lock dir containing pid. echo current process id file.  touch $lock_dir/pid.txt echo $$ > $lock_dir/pid.txt  # rest of script below 

checking /proc/ , cmdline call - @ moment checking there isn't process process id , not if process script.

you still ps command - offer form of platform agnosticism.

command=$(ps -o comm= -p $pid) if [[ $command == my_process ]]     ..... 

note command line arguments ps limit command no header.


Comments