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