passfd test: Fix warnings.
[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 #include <sys/wait.h>
29
30 #include "macros.h"
31
32 int
33 main ()
34 {
35   int pair[2];
36   int ret;
37   pid_t pid;
38   int status;
39   int fdnull;
40   int fd;
41   struct stat st;
42
43   fdnull = open ("/dev/null", O_RDWR);
44   if (fdnull < 0)
45     {
46       perror ("Could not open /dev/null");
47       return 1;
48     }
49
50   ret = socketpair (AF_UNIX, SOCK_STREAM, 0, pair);
51   if (ret < 0)
52     {
53       perror ("socket pair failed");
54       return 2;
55     }
56
57   pid = fork ();
58   if (pid == -1)
59     {
60       perror ("fork");
61       return 3;
62     }
63   if (pid == 0)
64     {
65       ret = sendfd (pair[1], fdnull);
66       if (ret == -1)
67         {
68           perror ("sendfd");
69           return 64;
70         }
71       return 0;
72     }
73   /* father */
74   else
75     {
76       fd = recvfd (pair[0], 0);
77       if (fd == -1)
78         {
79           perror ("recvfd");
80           return 16;
81         }
82       ret = waitpid (pid, &status, 0);
83       if (ret == -1)
84         {
85           perror ("waitpid");
86           return 17;
87         }
88       ASSERT (ret == pid);
89
90       if (!WIFEXITED (status))
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 (ret < 0)
105         {
106           perror ("fstat");
107           return 80;
108         }
109       return 0;
110     }
111 }