This is harder than it seems. You should do as little as possible in your signal handler because in many versions of Perl you can crash in the signal handler due to non-reentrant system libraries. Beware also of slow system calls which may be automatically restarted after an alarm.

Notice that $x = <COM> will hang if you don't get a newline. So you may need to resort to sysread instead. Anyway, I hope the following example code may be of some use to you.

my $N = 10; # timeout in seconds my $out; # read into here # See Perl Cookbook 2nd edition, Recipe 16.21 # See also perlfaq8 "How do I timeout a slow event". # Read a chunk from file handle <COM>, timing out after $N seconds. # Return number of bytes read, 0 if EOF, -1 if timed out. sub read_for { my $diestr = 0; my $nbytes = 0; eval { local $SIG{ALRM} = sub { die "alarm clock restart" }; alarm($N); # schedule alarm in $N seconds eval { $nbytes = sysread(COM, $out, 1024); }; $diestr = $@ if $@; alarm(0); # cancel the alarm }; $diestr = $@ if $@; alarm(0); # race condition protection return $nbytes unless $diestr; return -1 if $diestr =~ /alarm clock restart/; die $diestr; } while (1) { my $nbytes = read_for(); if ($nbytes < 0) { print "timed out after $N seconds\n"; last; } elsif ($nbytes == 0) { print "eof\n"; last; } print "chunk='$out'\n"; }

In reply to Re: Serial I/O and time question by eyepopslikeamosquito
in thread Serial I/O and time question by shepner

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.