in reply to Re^2: Non-blocking Reads from Pipe Filehandle
in thread Non-blocking Reads from Pipe Filehandle
Wrong! Win32::API does no defined check.
Hm, Maybe you're right, but it doesn't seem to be necessary. With your insight about buffering & EOF and a little wrapping, this seems to work quite nicely:
#! perl -slw use strict; use Win32API::File qw[ GetOsFHandle ]; use Win32::API::Prototype; ApiLink( 'Kernel32', q[ BOOL PeekNamedPipe( HANDLE hNamedPipe, LPVOID lpBuffer, DWORD nBufferSize, LPDWORD lpBytesRead, DWORD *lpTotalBytesAvail, LPDWORD lpBytesLeftThisMessage ) ] ) or die $^E; sub readlineMaybe { my $fh = shift; my $osfh = GetOsFHandle( $fh ) or die $^E; my( $bufsize, $buffer, $cAvail, $read ) = ( 1024, chr(0)x1024, 0, +0 ); PeekNamedPipe( $osfh, $buffer, $bufsize, $read, $cAvail, 0 ) or $^E == 109 or die $^E; return if $^E == 109; my $eolPos = 1+index $buffer, $/; return '' unless $eolPos; sysread( $fh, $buffer, $eolPos ) or die $!; return $buffer; } my $cmd = 'perl -le"$|++;print localtime().q[: some text] and sleep 1 for 1..1 +0" |'; my $pid = open my $pipe, $cmd or die $!; while( defined( my $line = readlineMaybe( $pipe ) ) ) { Win32::Sleep( 100 ) and next unless $line; chomp $line; chop $line; ## Annoying! print "Got: '$line'"; } __END__ c:\test>buk-pipe.pl Got: 'Wed Oct 1 02:01:21 2008: some text' Got: 'Wed Oct 1 02:01:22 2008: some text' Got: 'Wed Oct 1 02:01:23 2008: some text' Got: 'Wed Oct 1 02:01:24 2008: some text' Got: 'Wed Oct 1 02:01:25 2008: some text' Got: 'Wed Oct 1 02:01:26 2008: some text' Got: 'Wed Oct 1 02:01:27 2008: some text' Got: 'Wed Oct 1 02:01:28 2008: some text' Got: 'Wed Oct 1 02:01:29 2008: some text' Got: 'Wed Oct 1 02:01:30 2008: some text'
The only annoying thing is the need for that chop in addition to chomp.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Non-blocking Reads from Pipe Filehandle
by ikegami (Patriarch) on Oct 01, 2008 at 02:07 UTC | |
by BrowserUk (Patriarch) on Oct 01, 2008 at 03:40 UTC | |
by ikegami (Patriarch) on Oct 01, 2008 at 04:00 UTC | |
by BrowserUk (Patriarch) on Oct 01, 2008 at 04:59 UTC | |
by ikegami (Patriarch) on Oct 01, 2008 at 05:31 UTC | |
by ikegami (Patriarch) on Oct 01, 2008 at 06:25 UTC | |
by BrowserUk (Patriarch) on Oct 01, 2008 at 07:34 UTC | |
by BrowserUk (Patriarch) on Oct 01, 2008 at 02:31 UTC |