tags:

views:

142

answers:

4

I wrote a Perl program which forks and calls a background program in the child process and has a endless while loop which does some stuff in the parent process. Now the while loop should be left when the background program in the child process terminates:

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

        # needs help: if program terminated, break
    }
}
A: 

I guess, exec() is blocking, so it wouldn't return before the program quits, but I may be wrong.

Dercsár
-1 No, the program uses `fork` before, so only one child process will use `exec`, which is just right.
sleske
+2  A: 

Well, fork gives your parent process the child's PID (which you dutifully retrieve in your code). This is precisely so the parent can look after the child.

To leave the loop when it terminates, you can use kill 0 $pid to check whether the child still exists. See perldoc -f kill.

sleske
The problem is that the process is becoming a zombie, so the command still returns true.
Rupert Jones
It works though, when setting $SIG{CHLD}='IGNORE' (see next answer)
Rupert Jones
+2  A: 
sateesh
Thanks for the tip. I combined it with the tip above
Rupert Jones
A: 

Depending on your application you can check from time to time if the child ended and the parent can finish then. You can use posix waitpid() with WNOHANG to do a no-blocking wait, or signals to check if your child is still running, or you can use pipes (check when it gets closed). Personally I would use waitpid(). There is a very good explanation with examples in perlipc.

Val