How to prevent a script from running simultaneously?

Viewed 45311

I want to prevent my script running more than once at a time.

My current approach is

  • create a semaphore file containing the pid of the running process
  • read the file, if my process-id is not in it exit (you never know...)
  • at the end of the processing, delete the file

In order to prevent the process from hanging, I set up a cron job to periodically check the file if its older then the maximum allowed running time and kills the process if it’s still running.

Is there a risk that I'm killing a wrong process?

Is there a better way to perform this as a whole?

0 Answers
Related