Skip to content

Instantly share code, notes, and snippets.

@limitusus
Created February 7, 2013 07:25
Show Gist options
  • Save limitusus/4729213 to your computer and use it in GitHub Desktop.
Save limitusus/4729213 to your computer and use it in GitHub Desktop.
Pass a file descriptor from a process to another process through an UNIX socket, with Socket::MsgHdr.
#!/usr/bin/env perl
use strict;
use warnings;
use Socket;
use Socket::MsgHdr;
use IO::Handle;
my ($parent, $child);
socketpair($parent, $child, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
if (fork) {
close $parent;
open my $fh, ">>/tmp/fugafuga" or die;
my $fd = fileno $fh;
my $outHdr = Socket::MsgHdr->new(buflen => 8192);
$outHdr->cmsghdr(SOL_SOCKET, SCM_RIGHTS, pack("i", $fd));
print "Parent: $fd\n";
sendmsg($child, $outHdr);
close $fh;
wait();
} else {
close $child;
print "CHILD\n";
my $flags = 0;
my $inHdr = Socket::MsgHdr->new(buflen=>8192, controllen=>256);
recvmsg($parent, $inHdr, $flags);
my ($level, $type, $data) = $inHdr->cmsghdr;
my $fd = unpack("i", $data);
print "Child: $fd\n";
my $fh = IO::Handle->new;
$fh->fdopen($fd, "a");
$fh->autoflush;
print $fh "test\n";
print "CHILD DONE\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment