Coleoid has asked for the wisdom of the Perl Monks concerning the following question:

How do I open a r/w named pipe as a file? *Should* be simple...

Details in reply.

  • Comment on How do I open a r/w named pipe as a file? *Should* be simple...

Replies are listed 'Best First'.
Re: How do I open a r/w named pipe as a file? *Should* be simple...
by Coleoid (Sexton) on Mar 29, 2001 at 01:32 UTC
    Details:

    I'm connecting to a 3rd party component, so I'm stuck with the named pipe.
    I was using the Win32::Pipe module, but at arbitrary times it crashes Perl. There's no update for it on CPAN since 96.

    I read in the docs that named pipes can be treated just like files, open, read, print, close. That sounds perfect, I don't need any functionality beyond that.

    When I do an 'open or die' it dies.

    I did check FAQs and docs and c.l.p.m archives, and found nothing germane. If I missed something there, a pointer will be plenty.
    --Thanks!

      Ah, a Win32 named pipe (in Unix it is trivial). Fetch Win32API::File (if it didn't come with your copy of Perl) and you can do this:

      use Win32API::File qw( createFile OsFHandleOpen ); my $h= createFile( "//./pipe/MyPipe", "r" ) or die "Can't read from pipe/MyPipe: $^E\n"; $^E= 0; # Clear possibly misleading errors out. OsFHandleOpen( FILE, $h, "r" ) or die "Can't associate Perl handle: $! ($^E)\n";
      and then just use FILE like you would any old Perl file handle. (See the module documentation for more details like how to open the pipe for write access or for read/write access, etc.)

              - tye (but my friends call me "Tye")
        Grand, that works beautifully. I would not have opened Win32API::File on my own. Just to wrap it up, it looks like this, once fit to my program:

        my $hPipe = createFile( $PIPE_NAME, "rwe" ) or die "Can't read from [$PIPE_NAME]: $^E\n"; $^E = 0; # Clear possibly misleading errors out. no strict 'subs'; OsFHandleOpen( PIPE, $hPipe, "rw" ) or die "Can't associate Perl handle: $! ($^E)\n"; use strict 'subs';
        The 'e' portion of the "rwe" arg to createFile() causes an error if the file doesn't already exist, which is the behavior I want. If the pipe server isn't running, I need to know.

        I expect there's a better way to quiet the complaint about the filehandle being a bareword, too.

        Since I'm not reporting $^E unless there's an error, is it necessary to clear it ahead of time?

        Thanks for the prompt answer to something that turned out trickier than I thought.