Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://975091]
help
Chatterbox?
[stevieb]: I'm working on it to fatten it up and make it more reliant so I can finalize my Raspberry Pi automated build system for that software :) It's all well and fun, until I try to make it work with Windows lol
[shmem]: "debugging a program is more difficult than to write it in the first place. If you code your program as smart as you are, you are, by definition, too dumb to debug it."
[stevieb]: I literally laughed. That's good :) Perhaps I just need to go climb another mountain and forget about it
shmem seeks a tate and smikes a pope

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2017-03-28 22:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Should Pluto Get Its Planethood Back?



    Results (342 votes). Check out past polls.