http://www.perlmonks.org?node_id=1066329

lightoverhead has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks:

I have a question regarding how to obtain pids for each command I put in background.

foreach(1..10) { system("$cmd &"); #... somehow to get pid of this system() call, $pid print "$cmd submitted with PID: $pid\n"; }

I am wondering how to to get PID of each system() call.

As I put them in background, so they return right way, I hope I can get the pid for each of the sumbitted $cmd

Replies are listed 'Best First'.
Re: is it possible to get PID for a command running background?
by VincentK (Beadle) on Dec 09, 2013 at 20:52 UTC

      I might add to VincentK's good pointer. That on *NIX systems you ought to be able to name the PID, and even choose the PID's location. Which should help considerably, in managing those processes.

      --Chris

      Yes. What say about me, is true.
      
Re: is it possible to get PID for a command running background?
by ikegami (Patriarch) on Dec 10, 2013 at 04:38 UTC

    You're using system to launch a shell to execute a shell command. Perl has no way no knowing if that command results in the launching of processes or what their PID would be.

    The simplest solution would be to launch the program yourself.

    use IPC::Open3 qw( open3 ); sub launch_in_background { my ($prog, @args) = @_; open(local *CHILD_STDIN, '<', '/dev/null') or die $!; if (!@args) { # Make sure $prog isn't interpreted as a shell command. @args = ('-c', 'exec "$1"', 'dummy', $prog); $prog = '/bin/sh'; } return open3('<&CHILD_STDIN', '>&STDOUT', '>&STDERR', $prog,@args); } my $pid1 = launch_in_background('prog', 'file1'); my $pid2 = launch_in_background('prog', 'file2');

    Don't forget to reap your children or set SIGCHLD to IGNORE when you launch them.

    IPC::Run3 or IPC::Run would provide more readable solutions.

      Thank you ikegami and other monks!

      Yes, it's my impression that we may not be able to get PID for a system() launched process.

        You missed the point.

        The system-launched process ends before system returns, so why would you want the PID of a process that no longer exists.

        You don't want the PID of the process launched by system; you want the PID of some process launched by the system-launched process.

        What would that be for system('foo & bar &')?