Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Process ID of qx

by ropey (Hermit)
on Mar 05, 2007 at 09:12 UTC ( #603176=perlquestion: print w/replies, xml ) Need Help??

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

Hi Guys, Maybe a simple question, is there any way to find the process ID which is returned by executing a qx command ?

Replies are listed 'Best First'.
Re: Process ID of qx
by virtualsue (Vicar) on Mar 05, 2007 at 09:43 UTC
    From within the same program? No, not really. qx/backticks works much like system, in that the execution of your program stops while the command in qx() is executed. When your program resumes execution, the qx() subprocess is gone. See perlop for greater detail on how it works. If you want to spawn child processes in a more flexible, asynchronous way, start by reading fork. Threads, Multi-Processing, and Inter-Process Communication (in Tutorials) provides some interesting research material.
Re: Process ID of qx
by Moron (Curate) on Mar 05, 2007 at 13:54 UTC
    Let's not forget that the process no longer exists after the qx completes. But anyway, you could do this using open instead of qx, e.g.: (updated to correct pipe direction)
    use POSIX ":sys_wait_h"; # e.g.: my ($pid, $listing) = pidqx( "ls" ); sub pidqx { # returns pid + the usual backtick result my $pid = open my $ph, "$_[0] |" or die "$!: $_[0]"; local $/ = undef(); my $backtick = <$ph>; close $ph; waitpid $pid, 0; return ( $pid, $backtick ); }

    -M

    Free your mind

      my $pid = open my $ph, "| $_[0]" or die "$!: $_[0]";

      Your open is opening for write instead of read. The command's output goes to STDOUT instead of to your variable. Try this:

      sub pidqx { # returns pid + the usual backtick result my ( $cmd ) = @_; my $pid = open my $ph, '-|', $cmd or die "$!: $cmd"; local $/ = undef(); my $backtick = <$ph>; close $ph; return ( $pid, $backtick ); }

      Also, you don't have to wait for the command to finish because close does that for you.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (3)
As of 2020-11-27 06:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?