Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the process I start with Perl's system() a child process?

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:

  1. from a Perl script, run a command-line utility that starts a service. The utility exits but the service stays.

  2. after some time, find that service's pid and wait on it.

fork/exec doesn't solve this, although it clears up the question.

like image 311
n-alexander Avatar asked Nov 28 '22 05:11

n-alexander


1 Answers

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.

like image 108
Liudvikas Bukys Avatar answered Dec 06 '22 12:12

Liudvikas Bukys