passfd: fix incorrect sendmsg arguments
[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 <signal.h>
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <unistd.h>
26 #include <sys/types.h>
27 #include <sys/socket.h>
28 #include <sys/stat.h>
29 #include <sys/wait.h>
30
31 #include "macros.h"
32
33 int
34 main ()
35 {
36   int pair[2];
37   int ret;
38   pid_t pid;
39   int status;
40   int fdnull;
41   int fd;
42   struct stat st;
43
44 #if HAVE_DECL_ALARM
45   /* Avoid hanging on failure.  */
46   signal (SIGALRM, SIG_DFL);
47   alarm (5);
48 #endif
49
50   fdnull = open ("/dev/null", O_RDWR);
51   if (fdnull < 0)
52     {
53       perror ("Could not open /dev/null");
54       return 1;
55     }
56
57   ret = socketpair (AF_UNIX, SOCK_STREAM, 0, pair);
58   if (ret < 0)
59     {
60       perror ("socket pair failed");
61       return 2;
62     }
63
64   pid = fork ();
65   if (pid == -1)
66     {
67       perror ("fork");
68       return 3;
69     }
70   if (pid == 0)
71     {
72       ret = sendfd (pair[1], fdnull);
73       if (ret == -1)
74         {
75           perror ("sendfd");
76           return 64;
77         }
78       return 0;
79     }
80   /* father */
81   else
82     {
83       fd = recvfd (pair[0], 0);
84       if (fd == -1)
85         {
86           perror ("recvfd");
87           return 16;
88         }
89       ret = waitpid (pid, &status, 0);
90       if (ret == -1)
91         {
92           perror ("waitpid");
93           return 17;
94         }
95       ASSERT (ret == pid);
96
97       if (!WIFEXITED (status))
98         {
99           fprintf (stderr, "Child does not normally exit\n");
100           return 65;
101         }
102       ret = WEXITSTATUS (status);
103       if (ret != 0)
104         {
105           fprintf (stderr, "Send fd fail\n");
106           return ret;
107         }
108
109       /* try to stat new fd */
110       ret = fstat (fd, &st);
111       if (ret < 0)
112         {
113           perror ("fstat");
114           return 80;
115         }
116       return 0;
117     }
118 }