How can I get notifications of the completion of a background process in Perl?

I wrote a Perl program that wags and calls a background program in a child process and has an infinite while loop that does some things in the parent process. Now the while loop should be left when the background program in the child process exits:

$pid = fork();
if ( !$pid ) {
    exec( "program args" );
} else {
    while ( 1 ) {
        # do something

        # needs help: if program terminated, break
    }
}
+3
source share
4 answers

Well, forkit gives your parent process a child PID (which you obediently get in your code). This is how a parent can keep track of a child.

To leave the loop when it completes, you can use kill 0 $pidto check if the child still exists. See perldoc -f kill.

+3

, CHLD, , . ( perl . perldoc perlipc).

- else, .

...
} else {
    $SIG{CHLD} = \&reaper
}

# hash to store exit status of child processes
our %child;    
sub reaper {
    my $x;
    while (($x = waitpid(-1,WNOHANG)) >0) {
        $child{$x} = $? >> 8;
    }
}

>

$SIG{CHLD}='IGNORE', , .

+2

, , . posix waitpid() WNOHANG , , , (, ). waitpid(). perlipc.

0
source

I assume that exec () is blocking, so it won’t return before the program closes, but I could be wrong.

-1
source

Source: https://habr.com/ru/post/1731180/


All Articles