Perl's system() starts a process, but breaks the parent/child relationship?
test.pl:
use POSIX;
system("./test.sh &");
my $pid = `ps -C test.sh -o pid=`;
print "pid: -$pid-\n";
waitpid($pid, 0);
test.sh:
while true
do
sleep 1
done
When I run test.pl, it finds and prints a correct pid of test.sh. But waitpid() returns -1 and test.pl exits. After test.pl exist, test.sh is still running.
It looks like test.sh is not a child of test.pl, which breaks waitpid(). Why does this happen and how to make system() behave? Is that because Perl clears children automatically? If yes, how can I solve a general task of waiting on a child explicitly?
Update:
answers below suggest using fork/exec. The initial problem is this:
from a Perl script, run a command-line utility that starts a service. The utility exits but the service stays.
after some time, find that service's pid and wait on it.
fork/exec doesn't solve this, although it clears up the question.
The test.sh process is not your child process. The system()
forked a shell (which is your child), that shell forked a child that ran the test.sh program. The shell that was your child exited.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With