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

I know how to find the process of my perl program -- getpid() or the $$ variable. Now how do I find the process id (pid) of a program that I started? ie: system("some_program &"); I believe there is some convuluted way to do this in C using fork and exec, but I figured that must be an easy Perl way Y/n?

Replies are listed 'Best First'.
Re: Process ID of launched program?
by Anonymous Monk on Mar 02, 2000 at 01:24 UTC
    It's very easy. If successful, fork returns the pid of the child process. Thus, you can do something like:
    die "fork: $!" unless defined ($pid = fork); if ($pid) { # this is the parent process # do something parental } else { # this is the child process # do something childish }
      I wish I'd logged in for that. It was a good answer. :)
Re: Process ID of launched program?
by btrott (Parson) on Mar 02, 2000 at 01:36 UTC
    ... And, since the OP wanted to actually start up a new process, he/she can do that in the child using exec--the new process will take the process ID of the child.

    So, in your child, do this:

    exec "new_process";
    And that new_process will have the pid stored in $pid (in the parent).
      THANKS PERL MONKS!!! The fork() and exec() functions together will allow me to launch a program and find its pid. I'll try and post my Perl program load managing program to the "code" section after I write it.
Re: Process ID of launched program?
by Anonymous Monk on Mar 02, 2000 at 01:39 UTC
    Thank you, but that's not exactly what I am looking for. Actually, maybe it 'might' work with some changes. Basically, I want my Perl program to start another program (say a C program that I wrote). I want to get the pid of the program (without doing something cheesy like using ps and grepping for the prog name). The whole point is that I want to write a Perl program that launches programs and moniters how much CPU utilization the program is using. If the program is using too much of the CPU my perl program will renice() it. If the system load is still to high I'll pause my program and have the perl prog restart it when the load lightens up. Heck, this would be a good code kluge to give slash-dotted sights :-)
      This is exactly I want to do using perl. Can i do something like this in perl (this will work in C shell) - ./a.out & echo $! > /tmp/pid_file; thanks !!