]> granicus.if.org Git - postgresql/blob - src/backend/port/win32/signal.c
b99408ca0a1ac4c8017522683f5eb877b52430a3
[postgresql] / src / backend / port / win32 / signal.c
1 /*-------------------------------------------------------------------------
2  *
3  * signal.c
4  *        Microsoft Windows Win32 Signal Emulation Functions
5  *
6  * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7  *
8  * IDENTIFICATION
9  *        $PostgreSQL: pgsql/src/backend/port/win32/signal.c,v 1.20 2008/01/01 19:45:51 momjian Exp $
10  *
11  *-------------------------------------------------------------------------
12  */
13
14 #include "postgres.h"
15
16 #include <libpq/pqsignal.h>
17
18 /*
19  * These are exported for use by the UNBLOCKED_SIGNAL_QUEUE() macro.
20  * pg_signal_queue must be volatile since it is changed by the signal
21  * handling thread and inspected without any lock by the main thread.
22  * pg_signal_mask is only changed by main thread so shouldn't need it.
23  */
24 volatile int pg_signal_queue;
25 int                     pg_signal_mask;
26
27 HANDLE          pgwin32_signal_event;
28 HANDLE          pgwin32_initial_signal_pipe = INVALID_HANDLE_VALUE;
29
30 /*
31  * pg_signal_crit_sec is used to protect only pg_signal_queue. That is the only
32  * variable that can be accessed from the signal sending threads!
33  */
34 static CRITICAL_SECTION pg_signal_crit_sec;
35
36 static pqsigfunc pg_signal_array[PG_SIGNAL_COUNT];
37 static pqsigfunc pg_signal_defaults[PG_SIGNAL_COUNT];
38
39
40 /* Signal handling thread function */
41 static DWORD WINAPI pg_signal_thread(LPVOID param);
42 static BOOL WINAPI pg_console_handler(DWORD dwCtrlType);
43
44
45 /*
46  * pg_usleep --- delay the specified number of microseconds, but
47  * stop waiting if a signal arrives.
48  *
49  * This replaces the non-signal-aware version provided by src/port/pgsleep.c.
50  */
51 void
52 pg_usleep(long microsec)
53 {
54         if (WaitForSingleObject(pgwin32_signal_event,
55                                                         (microsec < 500 ? 1 : (microsec + 500) / 1000))
56                 == WAIT_OBJECT_0)
57         {
58                 pgwin32_dispatch_queued_signals();
59                 errno = EINTR;
60                 return;
61         }
62 }
63
64
65 /* Initialization */
66 void
67 pgwin32_signal_initialize(void)
68 {
69         int                     i;
70         HANDLE          signal_thread_handle;
71
72         InitializeCriticalSection(&pg_signal_crit_sec);
73
74         for (i = 0; i < PG_SIGNAL_COUNT; i++)
75         {
76                 pg_signal_array[i] = SIG_DFL;
77                 pg_signal_defaults[i] = SIG_IGN;
78         }
79         pg_signal_mask = 0;
80         pg_signal_queue = 0;
81
82         /* Create the global event handle used to flag signals */
83         pgwin32_signal_event = CreateEvent(NULL, TRUE, FALSE, NULL);
84         if (pgwin32_signal_event == NULL)
85                 ereport(FATAL,
86                                 (errmsg_internal("failed to create signal event: %d", (int) GetLastError())));
87
88         /* Create thread for handling signals */
89         signal_thread_handle = CreateThread(NULL, 0, pg_signal_thread, NULL, 0, NULL);
90         if (signal_thread_handle == NULL)
91                 ereport(FATAL,
92                                 (errmsg_internal("failed to create signal handler thread")));
93
94         /* Create console control handle to pick up Ctrl-C etc */
95         if (!SetConsoleCtrlHandler(pg_console_handler, TRUE))
96                 ereport(FATAL,
97                                 (errmsg_internal("failed to set console control handler")));
98 }
99
100 /*
101  * Dispatch all signals currently queued and not blocked
102  * Blocked signals are ignored, and will be fired at the time of
103  * the sigsetmask() call.
104  */
105 void
106 pgwin32_dispatch_queued_signals(void)
107 {
108         int                     i;
109
110         EnterCriticalSection(&pg_signal_crit_sec);
111         while (UNBLOCKED_SIGNAL_QUEUE())
112         {
113                 /* One or more unblocked signals queued for execution */
114                 int                     exec_mask = UNBLOCKED_SIGNAL_QUEUE();
115
116                 for (i = 0; i < PG_SIGNAL_COUNT; i++)
117                 {
118                         if (exec_mask & sigmask(i))
119                         {
120                                 /* Execute this signal */
121                                 pqsigfunc       sig = pg_signal_array[i];
122
123                                 if (sig == SIG_DFL)
124                                         sig = pg_signal_defaults[i];
125                                 pg_signal_queue &= ~sigmask(i);
126                                 if (sig != SIG_ERR && sig != SIG_IGN && sig != SIG_DFL)
127                                 {
128                                         LeaveCriticalSection(&pg_signal_crit_sec);
129                                         sig(i);
130                                         EnterCriticalSection(&pg_signal_crit_sec);
131                                         break;          /* Restart outer loop, in case signal mask or
132                                                                  * queue has been modified inside signal
133                                                                  * handler */
134                                 }
135                         }
136                 }
137         }
138         ResetEvent(pgwin32_signal_event);
139         LeaveCriticalSection(&pg_signal_crit_sec);
140 }
141
142 /* signal masking. Only called on main thread, no sync required */
143 int
144 pqsigsetmask(int mask)
145 {
146         int                     prevmask;
147
148         prevmask = pg_signal_mask;
149         pg_signal_mask = mask;
150
151         /*
152          * Dispatch any signals queued up right away, in case we have unblocked
153          * one or more signals previously queued
154          */
155         pgwin32_dispatch_queued_signals();
156
157         return prevmask;
158 }
159
160
161 /* signal manipulation. Only called on main thread, no sync required */
162 pqsigfunc
163 pqsignal(int signum, pqsigfunc handler)
164 {
165         pqsigfunc       prevfunc;
166
167         if (signum >= PG_SIGNAL_COUNT || signum < 0)
168                 return SIG_ERR;
169         prevfunc = pg_signal_array[signum];
170         pg_signal_array[signum] = handler;
171         return prevfunc;
172 }
173
174 /* Create the signal listener pipe for specified pid */
175 HANDLE
176 pgwin32_create_signal_listener(pid_t pid)
177 {
178         char            pipename[128];
179         HANDLE          pipe;
180
181         snprintf(pipename, sizeof(pipename), "\\\\.\\pipe\\pgsignal_%u", (int) pid);
182
183         pipe = CreateNamedPipe(pipename, PIPE_ACCESS_DUPLEX,
184                                            PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
185                                                    PIPE_UNLIMITED_INSTANCES, 16, 16, 1000, NULL);
186
187         if (pipe == INVALID_HANDLE_VALUE)
188                 ereport(ERROR,
189                                 (errmsg("could not create signal listener pipe for pid %d: error code %d",
190                                                 (int) pid, (int) GetLastError())));
191
192         return pipe;
193 }
194
195
196 /*
197  * All functions below execute on the signal handler thread
198  * and must be synchronized as such!
199  * NOTE! The only global variable that can be used is
200  * pg_signal_queue!
201  */
202
203
204 void
205 pg_queue_signal(int signum)
206 {
207         if (signum >= PG_SIGNAL_COUNT || signum <= 0)
208                 return;
209
210         EnterCriticalSection(&pg_signal_crit_sec);
211         pg_signal_queue |= sigmask(signum);
212         LeaveCriticalSection(&pg_signal_crit_sec);
213
214         SetEvent(pgwin32_signal_event);
215 }
216
217 /* Signal dispatching thread */
218 static DWORD WINAPI
219 pg_signal_dispatch_thread(LPVOID param)
220 {
221         HANDLE          pipe = (HANDLE) param;
222         BYTE            sigNum;
223         DWORD           bytes;
224
225         if (!ReadFile(pipe, &sigNum, 1, &bytes, NULL))
226         {
227                 /* Client died before sending */
228                 CloseHandle(pipe);
229                 return 0;
230         }
231         if (bytes != 1)
232         {
233                 /* Received <bytes> bytes over signal pipe (should be 1) */
234                 CloseHandle(pipe);
235                 return 0;
236         }
237         WriteFile(pipe, &sigNum, 1, &bytes, NULL);      /* Don't care if it works or
238                                                                                                  * not.. */
239         FlushFileBuffers(pipe);
240         DisconnectNamedPipe(pipe);
241         CloseHandle(pipe);
242
243         pg_queue_signal(sigNum);
244         return 0;
245 }
246
247 /* Signal handling thread */
248 static DWORD WINAPI
249 pg_signal_thread(LPVOID param)
250 {
251         char            pipename[128];
252         HANDLE          pipe = pgwin32_initial_signal_pipe;
253
254         snprintf(pipename, sizeof(pipename), "\\\\.\\pipe\\pgsignal_%u", GetCurrentProcessId());
255
256         for (;;)
257         {
258                 BOOL            fConnected;
259                 HANDLE          hThread;
260
261                 if (pipe == INVALID_HANDLE_VALUE)
262                 {
263                         pipe = CreateNamedPipe(pipename, PIPE_ACCESS_DUPLEX,
264                                            PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
265                                                            PIPE_UNLIMITED_INSTANCES, 16, 16, 1000, NULL);
266
267                         if (pipe == INVALID_HANDLE_VALUE)
268                         {
269                                 write_stderr("could not create signal listener pipe: error code %d; retrying\n", (int) GetLastError());
270                                 SleepEx(500, FALSE);
271                                 continue;
272                         }
273                 }
274
275                 fConnected = ConnectNamedPipe(pipe, NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
276                 if (fConnected)
277                 {
278                         hThread = CreateThread(NULL, 0,
279                                                   (LPTHREAD_START_ROUTINE) pg_signal_dispatch_thread,
280                                                                    (LPVOID) pipe, 0, NULL);
281                         if (hThread == INVALID_HANDLE_VALUE)
282                                 write_stderr("could not create signal dispatch thread: error code %d\n",
283                                                          (int) GetLastError());
284                         else
285                                 CloseHandle(hThread);
286                 }
287                 else
288                         /* Connection failed. Cleanup and try again */
289                         CloseHandle(pipe);
290
291                 /* Set up so we create a new pipe on next loop */
292                 pipe = INVALID_HANDLE_VALUE;
293         }
294         return 0;
295 }
296
297
298 /* Console control handler will execute on a thread created
299    by the OS at the time of invocation */
300 static BOOL WINAPI
301 pg_console_handler(DWORD dwCtrlType)
302 {
303         if (dwCtrlType == CTRL_C_EVENT ||
304                 dwCtrlType == CTRL_BREAK_EVENT ||
305                 dwCtrlType == CTRL_CLOSE_EVENT ||
306                 dwCtrlType == CTRL_SHUTDOWN_EVENT)
307         {
308                 pg_queue_signal(SIGINT);
309                 return TRUE;
310         }
311         return FALSE;
312 }