|Perl Monk, Perl Meditation|
Ensure Only One Instance of Your Script is Running... with 'ps -ef' ?by redapplesonly (Sexton)
|on Dec 05, 2022 at 22:06 UTC ( #11148582=perlquestion: print w/replies, xml )||Need Help??|
redapplesonly has asked for the wisdom of the Perl Monks concerning the following question:
Last week, I asked how to ensure that my Perl script wouldn't run if another instance of the same script was running. (Post was: "Mechanism for ensuring only one instance of a Perl script can only run?", Dec 2 2022) The solution that you guys suggested recommended taking advantage of flock() as a mechanism. (Thank you!!!) The basic implementation idea was simple: It my script ran and did not see an empty "lock file" in the local directory, it would create one and then flock() that file to lock it. Upon exiting, it would delete the file. If another instance of the same script ran and saw the lock file, it would immediately terminate. This was the "There Can Be Only One" (Highlander) approach.
I implemented this idea, but ran into management issues with the lock file. (The lock file was not deleted properly, it was overwritten, etc.) So I went back to the drawing board.
What do you think of this approach:
This code literally does what I would do; it issues a `ps -ef` and makes sure it is the only script of its instance running. No flock() command, no managing an external file.
I'm still a Perl newbie. To me, the above is simpler... perhaps too simple. You guys are the experts, so I'm (humbly) asking for a Pros-Vs-Cons critique of this idea. If I only want one instance of my script to run, is the above code a solid approach? All criticisms are welcome. Thank you!
Back to Seekers of Perl Wisdom