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

Dear Monks

I have written a perl-daemon script to which other perl script can connect to using a socket. All this work great.
However, I tried the following which didn't work
my $sock = new IO::Socket::INET ( ... ) my $ns = $sock->accept() ; { local *STDOUT ; open STDOUT, '>', $ns or die "Nope: $!\n"; print "thnx for usign me\n\n" ; # send message to client #print $ns "thnx for usign me\n\n" ; # this works } close($sock);
So, its the open call that doesn't do what I would like to have.
Any suggestions ? ( I also tried to use \$ns in the open statement -> same problem)

Thnx a lot

ps If needed I can make a working example!!

UPDATE: &> is what I need, thnx. but Net::Server is probably better!!

Replies are listed 'Best First'.
Re: howto redirect STDOUT to $socket
by monarch (Priest) on Sep 06, 2007 at 07:52 UTC
    Have a look at the post_accept() routine in Server.pm in the module Net::Server. You might even find Net::Server is exactly what you are looking for (as it has all the code for creating a daemon, and then switching the socket to STDIN/STDOUT before handing it to your callback function).

    Something along the lines of:

    if( defined $fileno ){ open STDIN, "<&$fileno" or die "Couldn't open STDIN to the client socket: $!"; open STDOUT, ">&$fileno" or die "Couldn't open STDOUT to the client socket: $!"; } else { *STDIN= \*{ $sock }; *STDOUT= \*{ $sock }; } STDIN->autoflush(1); STDOUT->autoflush(1);
    (untested).
Re: howto redirect STDOUT to $socket
by salva (Canon) on Sep 06, 2007 at 08:22 UTC
    use mode >& instead of > to (re)open STDOUT:
    open STDOUT, '>&', $ns or die "Nope: $!\n";
Re: howto redirect STDOUT to $socket (local*)
by tye (Sage) on Sep 06, 2007 at 13:14 UTC

    Note that the "local *STDOUT;" would prevent the proper use of '>&' from making file descriptor (fileno) 1 redirected to the socket. And that would mean that C code (such as module XS code) or external code (such as run via exec or system) would not write to the socket when it wrote to its STDERR equivalent.

    So it is better to use the sample code from open for saving and then restoring STDOUT instead of using the seductively simple "local *STDOUT;". I'll also note that manipulating symbol-table globs that contain open file handles will often have even worse results so I consider it something one should avoid unless one clearly understands exactly why it should be avoided.

    - tye        

    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: howto redirect STDOUT to $socket
by Anonymous Monk on Sep 06, 2007 at 08:01 UTC
    IO::Select?