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

I want to find out how to get the process id of a program I launch using system command in perl. For example test.pl has system("foo.exe arg1") ; How do I get the process id for foo.exe that I launched?

Replies are listed 'Best First'.
Re: Getting PID's
by zigdon (Deacon) on Oct 15, 2002 at 19:15 UTC

    I think you can't, directly. You could have your process write out it's pid to a file, and read it from your perl script - but since execution won't resume on the perl script anyway, until the process has ended, it's PID will be meaningless.

    It's possible that you can do something with fork and exec:

    perl -le ' if ($pid=fork) { print "pid: $pid"; exit; } exec ("echo new pid: \$\$"); '

    -- Dan

Re: Getting PID's
by dws (Chancellor) on Oct 15, 2002 at 19:33 UTC
    Assuming you're on a *nix box, the straightforward way of getting the process ID of a child process is to do the fork()/exec() yourself.

      Update: Thanks to dws (++!), I stand corrected.

      I'm not convinced that you'll be able to get the PID of the command which is being exec()'d. Sure, fork() returns it's PID to the parent, but that's still only given you the PID of the perl process that is going to be doing the exec("command"), not the PID of command itself.

      I've had a quick look at IPC::Open3 - it returns the PID of the child process, but I'm not sure if it's the fork()'ed perl process, or the external command.
      Unfortunately I've not got time to look in that further right now - it is left as an exercise for the reader :-)

      Cheers,

      BazB

        I'm not convinced that you'll be able to get the PID of the command which is being exec()'d.

        exec() doesn't change the process id.

Re: Getting PID's
by bnanaboy (Beadle) on Oct 15, 2002 at 19:18 UTC
    Would depend on the platform you're running on...

    In Unix, I believe it's

    ps -ef | grep 'foo.exe'

    ps is the unix command to list processes currently running. The switch -ef shows extended information for all processes currently running for all users. If the program is running under your username, then just use ps with no options and you'll have less to sort through.

    This is assuming the process is still running in the background and you have access to a command prompt.

      Rather than using a system call to ps and grep, you could do the whole thing in perl using Proc::ProcessTable.

      BazB