xref: /openbsd/regress/usr.sbin/ospfd/testfd.pl (revision 5af055cd)
1#!/usr/bin/perl
2#	$OpenBSD: testfd.pl,v 1.2 2014/07/11 22:28:51 bluhm Exp $
3
4# Copyright (c) 2014 Alexander Bluhm <bluhm@openbsd.org>
5#
6# Permission to use, copy, modify, and distribute this software for any
7# purpose with or without fee is hereby granted, provided that the above
8# copyright notice and this permission notice appear in all copies.
9#
10# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
18# Test file descriptor passing with the Perl xs module PassFd.
19
20use strict;
21use warnings;
22use Socket;
23use Fcntl qw(F_SETFD FD_CLOEXEC);
24use PassFd qw(sendfd recvfd);
25use POSIX qw(_exit);
26
27socketpair(my $parent, my $child, AF_UNIX, SOCK_STREAM, PF_UNSPEC)
28    or die "socketpair failed: $!";
29$child->fcntl(F_SETFD, 0)
30    or die "fcntl setfd failed: $!";
31
32defined(my $pid = fork())
33    or die "fork failed: $!";
34unless ($pid) {
35    # child process
36    close($parent)
37	or do { warn "Close parent socket failed: $!"; _exit(1); };
38    open(my $fd, '<', $0)
39	or do { warn "Open $0 failed: $!"; _exit(1); };
40    sendfd($child, $fd)
41	or do { warn "Sendfd failed: $!"; _exit(1); };
42    _exit(0);
43}
44# parent process
45close($child)
46    or die "Close child socket failed: $!";
47my $fd = recvfd($parent)
48    or die "Recvfd failed: $!";
49wait()
50    or die "Wait failed: $!";
51$? == 0
52    or die "Child process failed: $?";
53
54defined (my $line = <$fd>)
55    or die "Read from fd failed: $!";
56$line =~ /perl/
57    or die "Could not read perl from fd: $line\n";
58
59warn "Passing fd successful\n";
60exit 0;
61