Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm a litte bit confused about the interaction between Term::Readkey and waitpid. I hope someone can make me understand what's going on here.

so here's my problem:
There's a program running in a child process which is controlled by the parent waiting for a keystroke or waiting for the child to terminate. I've set the ReadMode to raw.
this code works:
while ( (not defined ($key = ReadKey (-1))) && ($dead != -1) ) { $dead = waitpid(-1,&WNOHANG); }

$dead returns -1 if the child terminates

but this one fails:
while ( (not defined ($key = ReadKey (0))) && ($dead != -1) ) { $dead = waitpid(-1,&WNOHANG); }

$dead returns 0 even if the child terminates

I don't want to use the first code-snipplet because my CPU usage increases up to 80% :(

tnx for any comment

Replies are listed 'Best First'.
Re: Term::Readkey and waitpid
by gregorovius (Friar) on May 16, 2000 at 11:12 UTC
    The ReadKey(0) in your second example blocks, which means that your program sleeps until a key is read from standard input. The waitpid() call is not executed until a key is pressed, which can happen long time after the child terminates.

    Your first snippet takes so many cpu cycles because both calls are non-blocking, which means that the program keeps calling them until one of the events they poll for happens, with the added disadvantage of slowing down execution of the child you're waiting for.

    In order to fix this you could have your program sleep for some milliseconds on each iteration (see perl functions sleep and select) or you could install a handler for the CHLD signal, which is just a subroutine that gets called whenever a child of your process terminates (see the perlipc manpage).
Re: Term::Readkey and waitpid
by slayven (Pilgrim) on May 16, 2000 at 02:48 UTC
    just in case you believe I'm impolite not to mention my name - I just forgot to login :)
    slayven