How can I get the process id of a UNIX command that is being run in a Perl script?

I am running a UNIX command in a Perl script.

I need the process id of a UNIX command.

For example, if I run below UNIX command:

# padv -s adv.cfg > adv.out &
[1] 4550

      

My process ID is 4550.

# ps -ef | grep padv
root      4550  2810  0 16:28 pts/5    00:00:00 padv -s adv.cfg
root      4639  2810  0 16:29 pts/5    00:00:00 grep padv

      

How do I capture this process ID in my Perl Script?

For example, I run my command in a Perl script as shown below:

#!/usr/bin/perl

use strict;
use warnings;

qx(padv -s adv.cfg > adv.out &);

      

+2


source to share


2 answers


you can use open()

Open returns nonzero on success and undefined. If open includes a pipe, the return value is the pid of the subprocess.

my $pid = open(my $ph, "-|", "padv -s adv.cfg > adv.out") or die $!;

      



outputting output from a $ph

file descriptor instead of redirecting output:

my $pid = open(my $ph, "-|", "padv -s adv.cfg") or die $!;

      

+4


source


Call fork

to create a child process. The process ID of the child process is returned to the parent process. The child process can then call exec

to execute the program you want.



+3


source







All Articles