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

r.joseph has asked for the wisdom of the Perl Monks concerning the following question:

Hello all - this is probably a easy question to answer, but I cannot seem to figure it out.

I need to launch a system process by a perl program (in my case, the program is called "root-tail") and get the Process ID for that program back so that I can save it to a file. Now, I am doing the fork()/exec() method:
die "Fork is bad: $!" unless defined ($pid = fork); if ($pid) { saveToFile($pid); } else { exec("root-tail","arg1","arg2"); }

Now, there are probably about ten arguments to "root-tail", and have them all just strung together in the exec() call, like above. However, when I save the PID to a file, and then go back and compare this PID with the PID of the process that is ACTUALLY RUNNING (via a call to 'ps'), the actual process id is always one higher: if my file that I saved to says 150, the actual pid is 151.

Does anyone know why this would happen? The perldoc's say that if there is a list of args to exec(), the shell will not be used at all, so why is there more than one process running, creating the one-up PID for my actual process?

Thanks for the help!

r. j o s e p h
"Violence is a last resort of the incompetent" - Salvor Hardin, Foundation by Issac Asimov

Replies are listed 'Best First'.
Re: Exec() and getting system PID
by kjherron (Pilgrim) on Jan 14, 2002 at 03:01 UTC
    The first thing that comes to mind is that the root-tail program itself forks, with the parent process exiting and the child process continuing on. This child process is what you're seeing when you run ps.

    What happens when you run root-tail directly from the command line? Does it just do its work and then exit, or does it put itself in the background and run for a while? If it's the latter, this is accomplished by forking as I outlined above.

Re: Exec() and getting system PID
by hossman (Prior) on Jan 14, 2002 at 12:09 UTC
    Is this the program you are using?

    If so, are you sure you aren't using the "-f|-fork" option?

    My guess is, you should use my $pidline = `root-tail -f ...` but for some reason, root-tail v0.0.10 has the line for printing the PID commented out...

    pid = fork (); if (pid != 0) { /*printf ("forking mode: pid=%d\n", pid);*/ exit (0); }
    (You may want to mail the devloper and ask what gives.)

    However, if you don't use -f, the code you have above seems to work just fine.

Re: Exec() and getting system PID
by metadoktor (Hermit) on Jan 14, 2002 at 03:07 UTC
    kjherron is correct. It is almost certain that your root-tail program is creating a child process and exiting.

    metadoktor

    "The doktor is in."