Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

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.


Comment on Re: is it possible to get PID for a command running background?
Select or Download Code
Re^2: is it possible to get PID for a command running background?
by lightoverhead (Monk) 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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1066375]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2014-08-30 02:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (291 votes), past polls