Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Re: is it possible to get PID for a command running background?

by ikegami (Pope)
on Dec 10, 2013 at 04:38 UTC ( #1066375=note: print w/replies, xml ) Need Help??

in reply to is it possible to get PID for a command running background?

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.

Replies are listed 'Best First'.
Re^2: is it possible to get PID for a command running background?
by lightoverhead (Pilgrim) on Dec 10, 2013 at 17:01 UTC

    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 &')?

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1066375]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (4)
As of 2017-12-17 03:48 GMT
Find Nodes?
    Voting Booth?
    What programming language do you hate the most?

    Results (462 votes). Check out past polls.