where did you assigned value to $pid ? :-)
You can also miss some data, for example @cmd can handle TERM signal and print partial result. @cmd also can block/not handle TERM signal (or in some case, cannot be KILLed).

Sample:

use strict; use warnings; use IO::Pipe; use constant TIMEOUT => 5; my @cmd = (); my $pipe = new IO::Pipe; if (my $pid = fork) { $pipe->reader; $SIG{ALRM} = sub { kill TERM => $pid; $SIG{ALRM} = sub { kill KILL => $pid; $SIG{ALRM} = sub { close $pipe; }; alarm TIMEOUT; }; alarm TIMEOUT; }; $SIG{CHLD} = sub { while (my $wait = wait) { alarm 0 if $wait == $pid; } }; # alarm here if you want force child to quit after TIMEOUT # alarm TIMEOUT; while (my $from_child = <$pipe>) { # alarm here if you want to interrupt child after inactivity # (no output lines) # alarm TIMEOUT; # ... }; alarm (0); close $pipe; } elsif (defined $pid) { # Child $pipe->writer; open STDOUT, '>&', $pipe; exec @cmd; } else { die "Fork failed: $!\n"; }

In reply to Re^2: fork - alarm - output by happy.barney
in thread fork - alarm - output by chart3399

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.