http://qs1969.pair.com?node_id=11148582

redapplesonly has asked for the wisdom of the Perl Monks concerning the following question:

Hola Monks,

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:

#!/usr/bin/perl use warnings; use strict; package main; my $name = `basename "$0"`; # Get this script's name $name =~ s/\R//g; # Chop off trailing newlines print "Script name is: \"$name\".\n"; my $dirPerl = "/usr/bin/perl"; my $psCmd = "ps -ef | grep $name"; my $scriptRunningCount = 0; my $output = qx($psCmd); # Run "ps -ef | grep SCRIPTNAME" foreach my $line (split /[\r\n]+/, $output) { if( index($line,$dirPerl) != -1 && index($line,$name) != -1 +){ $scriptRunningCount++; } } if($scriptRunningCount == 1){ # ...run script... } print "END OF PROGRAM.\n";

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!