973c5d88e140ad32e7652bcf1ddfa2e84590dca9
[gnulib.git] / tests / test-sigprocmask.c
1 /* Test of sigprocmask.
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 /* Written by Bruno Haible <bruno@clisp.org>, 2011.  */
18
19 #include <config.h>
20
21 #include <signal.h>
22
23 #include "signature.h"
24 SIGNATURE_CHECK (sigprocmask, int, (int, const sigset_t *, sigset_t *));
25
26 #include <errno.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <unistd.h>
30
31 #include "ignore-value.h"
32 #include "macros.h"
33
34 #if !((defined _WIN32 || defined __WIN32__) && !defined __CYGWIN__)
35
36 static volatile int sigint_occurred;
37
38 static void
39 sigint_handler (int sig)
40 {
41   sigint_occurred++;
42 }
43
44 int
45 main (int argc, char *argv[])
46 {
47   sigset_t set;
48   int pid = getpid ();
49   char command[80];
50
51   signal (SIGINT, sigint_handler);
52
53   sigemptyset (&set);
54   sigaddset (&set, SIGINT);
55
56   /* Check error handling.  */
57   ASSERT (sigprocmask (1729, &set, NULL) == -1);
58   ASSERT (errno == EINVAL);
59
60   /* Block SIGINT.  */
61   ASSERT (sigprocmask (SIG_BLOCK, &set, NULL) == 0);
62
63   /* Request a SIGINT signal from outside.  */
64   sprintf (command, "sh -c 'sleep 1; kill -%d %d' &", SIGINT, pid);
65   ignore_value (system (command));
66
67   /* Wait.  */
68   sleep (2);
69
70   /* The signal should not have arrived yet, because it is blocked.  */
71   ASSERT (sigint_occurred == 0);
72
73   /* Unblock SIGINT.  */
74   ASSERT (sigprocmask (SIG_UNBLOCK, &set, NULL) == 0);
75
76   /* The signal should have arrived now, because POSIX says
77        "If there are any pending unblocked signals after the call to
78         sigprocmask(), at least one of those signals shall be delivered
79         before the call to sigprocmask() returns."  */
80   ASSERT (sigint_occurred == 1);
81
82   return 0;
83 }
84
85 #else
86
87 /* On native Windows, getpid() values and the arguments that are passed to
88    the (Cygwin?) 'kill' program are not necessarily related.  */
89
90 int
91 main ()
92 {
93   fputs ("Skipping test: native Windows platform\n", stderr);
94   return 77;
95 }
96
97 #endif