add comments to clarify the initial handshake
[scpubgit/Tak.git] / lib / Tak / STDIOSetup.pm
CommitLineData
77bf1d9b 1package Tak::STDIOSetup;
2
7b71b06e 3use Log::Contextual qw(:log);
4use Log::Contextual::SimpleLogger;
77bf1d9b 5use Tak::ConnectionService;
6use Tak::Router;
7use Tak;
3e883325 8use IO::Handle;
77bf1d9b 9use strictures 1;
10
11sub run {
7b71b06e 12 open my $stdin, '<&', \*STDIN or die "Duping stdin: $!";
13 open my $stdout, '>&', \*STDOUT or die "Duping stdout: $!";
3e883325 14 $stdout->autoflush(1);
2791fd73 15 # if we don't re-open them then 0 and 1 get re-used - which is not
16 # only potentially bloody confusing but results in warnings like:
17 # "Filehandle STDOUT reopened as STDIN only for input"
7b71b06e 18 close STDIN or die "Closing stdin: $!";
19 open STDIN, '<', '/dev/null' or die "Re-opening stdin: $!";
20 close STDOUT or die "Closing stdout: $!";
21 open STDOUT, '>', '/dev/null' or die "Re-opening stdout: $!";
22 my ($host, $level) = @ARGV;
23 my $sig = '<'.join ':', $host, $$.'> ';
24 Log::Contextual::set_logger(
25 Log::Contextual::SimpleLogger->new({
26 levels_upto => $level,
27 coderef => sub { print STDERR $sig, @_; }
28 })
29 );
986f5290 30 my $done;
77bf1d9b 31 my $connection = Tak::ConnectionService->new(
32 read_fh => $stdin, write_fh => $stdout,
986f5290 33 listening_service => Tak::Router->new,
34 on_close => sub { $done = 1 }
77bf1d9b 35 );
2791fd73 36 $connection->receiver->service->register_weak(remote => $connection);
37 if ($0 eq '-') {
38 $0 = 'tak-stdio-node';
39 }
7b71b06e 40 log_debug { "Node starting" };
9df46eb8 41 # Tell the other end that we've finished messing around with file
42 # descriptors and that it's therefore safe to start sending requests.
43 print $stdout "Ssyshere\n";
986f5290 44 Tak->loop_until($done);
77bf1d9b 45}
46
471;