in reply to Re: How do you get PID of a program called using system call?
in thread How do you get PID of a program called using system call?

You should really check the return values from fork() and exec() or you can get yourself into a lot of mess.

If fork() was not able to fork, it will return undef and if exec() is not able to run the program it will return.

my $pid = fork(); if ($pid) { push @pids, $pid; } elsif (defined $pid) { exec($cmd); die "Cannot exec '$cmd': $!\n"; } else { die "Cannot fork: $!\n" }
Not catching the exec is potentially the most dangerous as the child process then continues in the loop, just the same as the parent. In this cas you would end up filling the process table.

Replies are listed 'Best First'.
Re: Re: Re: How do you get PID of a program called using system call?
by blakem (Monsignor) on Oct 08, 2001 at 23:36 UTC
    Good point. I certainly should have checked the return values. There is a large potential bug lying in wait there.

    I don't think this would ever fill up the proc table though, The loop is bound by a for (1..4) which means that in the wost case, we would have:

    1 parent through the first time (creates 1 child) 1 parent 1 child the second time (creates 2 children) 2 parents 2 children the third time (creates 4 children) 4 parents 4 children the fourth time (creates 8 children)
    So at most I see a possible 16 procs being active at once.... of course they might never exit due to the messed up @pids array, but thats another matter.

    Again, thanks for the catch.

    -Blake