I’m writing a Perl script (say script.pl) that calls another script newscript.pl. I want to get the PIDs of both the scripts in script.pl only. I can get the PID of script.pl by using following code
my $pid = Unix::PID->new();
my @p = $pid->get_pidof( $pid->get_command($$), 1 );
After this I call system to execute newscript.pl
system("perl newscript.pl");
I want to capture the PID generated by this newscript.pl in script.pl.
By the time
systemreturns, the spawned process will have already exited, leaving its pid as an interesting historical reference—useful for log analysis, for example.If you want the pids of both
script.plandnewscript.pl,forkand manage their lifetimes yourself. With more specific information about the problem you’re tackling, we could give you more specific suggestions.To block other instances of a program, a common technique is to use the operating system’s facility for cooperative locking: at startup, attempt to lock a certain file. If successful, your program knows it’s the only one. Otherwise, another process already has the lock, so the new process exits. See below for an example.
Note that you must keep the filehandle returned from
take_lockopen while control is inside your critical section. The code above treats it as an opaque token. When your program exits, Perl closes the filehandle, which releases the lock automatically. What you don’t want to do is calltake_lockin void context because that would discard your lock.