passfd module, part 4, tweaks.
[gnulib.git] / tests / test-passfd.c
1 /* Test of passing file descriptors.
2    Copyright (C) 2011 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17 #include <config.h>
18
19 #include "passfd.h"
20
21 #include <fcntl.h>
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <unistd.h>
25 #include <sys/types.h>
26 #include <sys/socket.h>
27 #include <sys/stat.h>
28
29 #include "macros.h"
30
31 int
32 main ()
33 {
34   int pair[2];
35   int ret;
36   pid_t pid;
37   int status;
38   int fdnull;
39   int fd;
40   struct stat st;
41
42   fdnull = open ("/dev/null", O_RDWR);
43   if (fdnull < 0)
44     {
45       perror ("Could not open /dev/null");
46       return 1;
47     }
48
49   ret = socketpair (AF_UNIX, SOCK_STREAM, 0, pair);
50   if (ret < 0)
51     {
52       perror ("socket pair failed");
53       return 2;
54     }
55
56   pid = fork ();
57   if (pid == -1)
58     {
59       perror ("fork");
60       return 3;
61     }
62   if (pid == 0)
63     {
64       ret = sendfd (pair[1], fdnull);
65       if (ret == -1)
66         {
67           perror ("sendfd");
68           return 64;
69         }
70       return 0;
71     }
72   /* father */
73   else
74     {
75       fd = recvfd (pair[0], 0);
76       if (fd == -1)
77         {
78           perror ("recvfd");
79           return 16;
80         }
81       ret = waitpid (pid, &status, 0);
82       if (ret == -1)
83         {
84           perror ("waitpid");
85           return 17;
86         }
87       ASSERT (ret == pid);
88
89       ret = WIFEXITED (status);
90       if (ret == 0)
91         {
92           fprintf (stderr, "Child does not normally exit\n");
93           return 65;
94         }
95       ret = WEXITSTATUS (status);
96       if (ret != 0)
97         {
98           fprintf (stderr, "Send fd fail\n");
99           return ret;
100         }
101
102       /* try to stat new fd */
103       ret == fstat (fd, &st);
104       if (0 != ret)
105         {
106           perror ("fstat");
107           return 80;
108         }
109       return 0;
110     }
111 }