Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re: Acting like (x)inetd

by mantager (Sexton)
on Jun 08, 2012 at 06:51 UTC ( #975091=note: print w/ replies, xml ) Need Help??

in reply to Acting like (x)inetd

Ok, I'll answer myself on this, just in case someone comes here later searching for an answer.

The easiest way I found to do this is way easier than I thought: just connect STDIN, STDOUT and STDERR to the socket of the accepted connection and then leave the control to the child process. Here is an example implementation that just uses cat to verify the script is working:

#!/usr/bin/env perl use strict; use warnings; use Socket qw/TCP_NODELAY/; use IO::Socket::INET; my @cmd = (qw(/bin/cat)); my $sock = IO::Socket::INET::->new( Listen => 20, LocalAddr => '', LocalPort => 20202, Proto => 'tcp', Reuse => 1, ); die "Unable to create socket: $!" unless $sock; $sock->sockopt(TCP_NODELAY, 1); $SIG{CHLD} = 'IGNORE'; while (1) { # Go on forever! my $client = $sock->accept(); # Blocking my $child = fork(); next unless defined $child; # Not enough resources to fork() - +ignore silently if ($child) { # I'm the parent close($client); next; } else { # I'm the child, I serve this connection close($sock); open (STDIN, "<&".fileno($client)) or die "Cannot dup STDIN to connection: $!"; open (STDOUT,">&".fileno($client)) or die "Cannot dup STDOUT to connection: $!"; open (STDERR,">&".fileno($client)) or die "Cannot dup STDERR to connection: $!"; # Now leave the rest to CHILD process exec(@cmd); } }

A simple telnet localhost 20202 will echo back any string you write on it.


Comment on Re: Acting like (x)inetd
Select or Download Code

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://975091]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (11)
As of 2015-07-30 19:32 GMT
Find Nodes?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...

    Results (273 votes), past polls