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).

In reply to Re: Term::Readkey and waitpid by gregorovius
in thread Term::Readkey and waitpid by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.