in reply to getting a child's process ID

Sorry to revive this, but I have a problem with the way my code is working and it is related to this issue.

I am using the same if...fork...else...exec process as @davorg but when I look at the ps -ef output I find 2 processes.

if(my $pid = fork()){ $this->set_pid_in_db($id, $pid); } # Child process starts service and inherits child PID else{ my $command = sprintf("%s %s 1>>%s 2>>%s", $this->fnClient(), $id, + $this->fnOe($id), $this->fnOe($id)); #my $command = sprintf("%s %s", $this->fnClient(), $id); exec($command); } >ps -ef | grep SB mark 11970 1 0 07:57 pts/1 00:00:00 sh -c /code/SBClient2.pl j +ob1 1>>/log/log.1.oe 2>>/log/log.1.oe mark 11971 11970 77 07:57 pts/1 00:00:06 /usr/bin/perl /code/SBClie +nt2.pl job1

And the PID that was set on line 2 is 11970 rather than 11971. Of course, I can still test to see if 11970 is running and that will tell me if 11971 is running. And I can kill 11970 and that will kill 11971.

However, what confuses me is that if I don't redirect output and error to a file (i.e. use the commented out command instead), then 1 process rather than 2 processes are started.

Does anyone know why this happens?

Replies are listed 'Best First'.
Re^2: getting a child's process ID
by Corion (Patriarch) on Jan 09, 2015 at 13:23 UTC

    If Perl finds something in the command line for exec or system that it can't interpret (like a redirection), it will invoke the shell to parse the command. This is what's happening here.

    As a solution, you could either do the redirect yourself by reopening STDERR to the file or restructure your approach so that you get the correct PID into the appropriate place.

      Thanks for the reply. The idea is to make this code independent of what it is running. It seems every day my argument for using perl gets weaker and weaker.

        If you don't want Perl to insert a shell between your program and the child process, then you'll have to filter out all the redirection etc. yourself.

        The alternative is to restructure your process in such a way that it always expects two processes.

        As you haven't told us much about your problem, I can't really help you here. Maybe you want to post a new thread via SoPW where you describe the actual problem you're trying to solve. Then maybe somebody can propose alternatives that allow you to accomplish your goal.