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

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

How to get to know the process id of a process started using a system call. What I am doing in a script is
... ... ... if (fork()) { while (1) { system(<Launching a java process>); ... on some failure condition break the loop; } }
Now I want to get to know the process id of the launched java process. What is to be done. -thanks Madan

2004-12-07 Janitored by Arunbear - added code tags, as per Monastery guidelines

Replies are listed 'Best First'.
Re: Process id
by chromatic (Archbishop) on Dec 07, 2004 at 05:57 UTC

    On my Linux box, calling exec in a child process doesn't create a new process, at least pid-wise. That is, if you can replace the system call with exec, you can use the return value of the fork in the parent for your pid.

    #! perl use strict; use warnings; my $child_pid = fork(); die "Couldn't fork: $!\n" unless defined $child_pid; if ($child_pid) { print "Child pid is $child_pid\n"; } else { exec( 'java ...' ); }
Re: Process id
by tachyon (Chancellor) on Dec 07, 2004 at 06:04 UTC

    One way is to do a fork/exec which is all system really is anyway:

    my $pid = fork (); die "Fork failed!\n" unless defined $pid; if ( $pid == 0 ) { # convert kid to java process exec( $path_to_java_process ); exit 0; # for clarity, we don't actually get here } # in the parent $pid holds PID of child which is (now) the java proces +s

    cheers

    tachyon

      If you're going to be launching processes yourself, don't forget to reap them as well. If you want to catch errors on exit, you'll probably want to call wait or waitpid to do that.