2

I am triggering a UNIX command in Perl script.

I need the process ID of the UNIX command.

For example if i trigger 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 to capture that process ID in my Perl Script?

For example, i am triggering my command in Perl script like below:

#!/usr/bin/perl

use strict;
use warnings;

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

2 Answers2

4

You could use open()

Open returns nonzero on success, the undefined value otherwise. If the open involved a pipe, the return value happens to be the pid of the subprocess.

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

reading output from $ph file handle instead of output redirect:

my $pid = open(my $ph, "-|", "padv -s adv.cfg") or die $!;
mpapec
  • 50,217
  • 8
  • 67
  • 127
  • Opening a pipe already creates a fork. You should lose the `&`. – tripleee Aug 22 '14 at 11:53
  • 2
    As mentioned, opening a pipe creates a fork, and so is already in the "background". No need for ampersand. You could also remove the redirect to adv.out and just read/process the output using the `$ph` file handle. – imran Aug 22 '14 at 15:04
3

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.

Oswald
  • 31,254
  • 3
  • 43
  • 68