Thread watchdog bei einer while-Schleife (20 answers)
Opened by perlensammler22 at 2015-09-22 07:29

hlubenow
 2015-09-24 21:27
#182378 #182378
User since
2009-02-22
877 Artikel
BenutzerIn
[default_avatar]
Also, hier nochmal ein Beispiel:
Code (perl): (dl )
1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/perl
use strict;
use warnings;

# datastream.pl - Print local time every three seconds.

$| = 1; # unbuffered STDOUT

while ( 1 ) {
    print scalar(localtime), "\n";
    sleep 3;
}

und
Code (perl): (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/usr/bin/perl

use warnings;
use strict;

# readstream.pl

use Fcntl;
fcntl(STDIN, F_SETFL, O_NONBLOCK);

my $input;
my $res;
my $str = "";
my $reading = 0;
my $notread = 0;
while(1) {
    $res = sysread(STDIN, $input, 1);
    if (defined($res)) {
        $reading = 1;
        $str .= $input;
        if ($notread) {
            print "Unsuccessful attempts to read: $notread.\n";
        }
        $notread = 0;
    } else {
        if ($reading == 1) {
            print $str;
        }
        $reading = 0;
        $notread++;
        $str = "";
    }
}

Aufruf:
Code: (dl )
datastream.pl | readstream.pl

Auf Linux liest er dann ungeblockt, und man kann mitzählen, wie oft er nichts gelesen hat (so daß man eine Zahl festlegen könnte, bei der er das Lesen abbrechen soll). Problem ist: In den drei Sekunden waren das bei mir ca. 4,5 Millionen mal! Irgendwo würde ich ihm da gern noch eine sleep-Pause gönnen.

View full thread watchdog bei einer while-Schleife