passfd module, part 4.
[pspp] / tests / test-passfd.c
1 /* Test of terminating the current process.
2    Copyright (C) 2010-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 /* Written by Bruno Haible <bruno@clisp.org>, 2010.  */
18
19 #include <config.h>
20 #include <stdlib.h>
21 #include <stdio.h>
22 #include <unistd.h>
23 #include "passfd.h"
24 #include <sys/types.h>
25 #include <sys/socket.h>
26 #include <sys/stat.h>
27 #include <fcntl.h>
28
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       ret = WIFEXITED (status);
91       if (ret == 0)
92         {
93           fprintf (stderr, "Child does not normally exit\n");
94           return 65;
95         }
96       ret = WEXITSTATUS (status);
97       if (ret != 0)
98         {
99           fprintf (stderr, "Send fd fail");
100           return ret;
101         }
102
103       /* try to stat new fd */
104       ret == fstat (fd, &st);
105       if (0 != ret)
106         {
107           perror("fstat:");
108           return 80;
109         }
110       return 0;
111     }
112 }