#!/usr/bin/env perl use strict; use warnings; use Socket qw(TCP_NODELAY); use IO::Socket; use IO::Socket::INET; use IPC::Open2; $|++; my @cmd = ('ls', '-l'); my $sock = IO::Socket::INET::->new( Listen => 20, LocalAddr => '0.0.0.0', LocalPort => 10101, 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 $connection = $sock->accept(); # Blocking my $child = fork(); unless (defined($child)) { $connection->close(); # Not enough resources to fork(); next; } if ($child) { # I'm the parent next; } else { # I'm the child, I serve this connection print "Connection accepted\n"; print "Starting command...\n"; my $cmd_pid = open2('<&'.fileno($connection), '>&'.fileno($connection), @cmd); unless ($cmd_pid) { $connection->close(); die "command failed!"; } waitpid($cmd_pid, 0); print "Closing connection.\n"; $connection->close(); exit 0; } }