How to get the PID of a process created using the Perl system function?

I am writing a Perl script (say script.pl ) that calls another script newscript.pl . I want to get the PID of both scripts only in script.pl . I can get the PID script.pl using the following code

 my $pid = Unix::PID->new(); my @p = $pid->get_pidof( $pid->get_command($$), 1 ); 

After that, I call system to run newscript.pl

 system("perl newscript.pl"); 

I want to capture the PID generated by this newscript.pl in script.pl .

+6
source share
2 answers

By the time system returns, the spawned process will already exit, leaving its pid as an interesting historical link, useful for log analysis, for example.

system LIST
system PROGRAM LIST

Exactly like exec LIST , except that fork is executed first and the parent process expects the child process to exit & hellip;

If you want the pids of both script.pl and newscript.pl , fork independently control their lifetimes. With more specific information about the problem that you can solve, we could give you more specific suggestions.


To block other instances of the program, a common method is to use the operating system. To ensure shared locking: at startup, try to lock a specific file. If successful, your program knows that this is the only one. Otherwise, another process already has a lock, so the new process ends. The following is an example.

 #! /usr/bin/env perl use strict; use warnings; use Fcntl qw/ :flock /; use File::Basename; use POSIX qw/ strftime /; $0 = basename $0; my $LOCK = "$ENV{HOME}/.lock-$0"; sub logmsg { my($msg) = @_; my $t = strftime "%F %T", localtime time; warn "$0: $t - $$ - $msg\n"; } sub take_lock { open my $fh, ">", $LOCK or die "$0: open $LOCK: $!"; unless (flock $fh, LOCK_EX | LOCK_NB) { logmsg "failed to lock $LOCK; exiting."; exit 1; } $fh; } my $token = take_lock; logmsg "processing..."; sleep 2 * 60; logmsg "done."; 

Note that you must leave the file descriptor returned from take_lock open while the control is inside your critical section . The above code treats it as an opaque token. When your program exits, Perl closes the file descriptor, which automatically releases the lock. What you do not want to do is call take_lock in the void context, because it will cancel your lock.

+5
source

The process number of the current process is in $$ . Use open3 instead of system to get the process number of the child process.

+9
source

Source: https://habr.com/ru/post/909070/


All Articles