Beefy Boxes and Bandwidth Generously Provided by pair Networks Cowboy Neal with Hat
Think about Loose Coupling
 
PerlMonks  

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 => '0.0.0.0', 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.

Cheers.


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

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (8)
As of 2014-04-20 09:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (485 votes), past polls