Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

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.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://975091]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2017-12-14 01:36 GMT
Find Nodes?
    Voting Booth?
    What programming language do you hate the most?

    Results (383 votes). Check out past polls.