1822480 Members
2523 Online
109642 Solutions
New Discussion юеВ

Perl script help

 
SOLVED
Go to solution
svilen888
Occasional Advisor

Perl script help


Please help me.
I need a secure way using Perl to check
whether the another example of main program is in the memory like process.
If another example is running,then not to start the program, else - to start.
But without using system("ps -ef | grep myprogram").
I need a clearly Perl-example.
Thanks for help.
liana
2 REPLIES 2
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Perl script help

Probably the most straightforward method is as your script starts, check for the existence of a file; e.g. /var/tmp/mygrogram.pid

If the file does not exist, then it is safe to continue. You create the file and write the PID of your current process into the file. Upon exit, remove the file.

If the file does exist, read the contents of the file to get the PID of the process that wrote it.
send a kill 0 to this process.
$rslt = kill 0,$other_pid;
if ($rslt)
{
exit(0); # currently running process
}
else
{ # process dead even though file exists
# unlink the original file
# create new PID file and write current PID
# do your thing
#

# remove PID file
exit($status);
}

I would also add signal handlers to remove this file.

If it ain't broke, I can fix that.
H.Merijn Brand (procura
Honored Contributor

Re: Perl script help

since there is NO WAY to return to the script after an exit, I do not understand why people write

if (expression) {
exit $status;
}
else {
some other code ...
}

this is IMHO cargo cult programming and only blurs the script. Just like

cat file | process

is unneccesarily taking system resources where

process < file

would do just as good.

expression and exit $status;

and go on with the real work

Clay, I realy enjoy your good answers, they are mostly short clear and to the point, but I just couldn't let this one go. sorry.

BTW I think that CPAN offers a nice bunch of Unix interaction moduls and functions on ftp://download.xs4all.nl/pub/mirror/CPAN/modules/by-module/Proc/ (Proc::ProcessTable is included in my builds), and there is even a complete HP-UX namespace: ftp://download.xs4all.nl/pub/mirror/CPAN/modules/by-module/HPUX/

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn