How to prevent a script from running simultaneously?

BashSemaphore

Bash Problem Overview


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?

Bash Solutions


Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOliView Question on Stackoverflow