blob: 8d6386793d4a57cf309f6201c80f92515ea632bc [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Raymond Hettinger722d8c32009-06-18 22:21:03 +00003from contextlib import closing
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +02004import enum
Christian Heimescc47b052008-03-25 14:56:36 +00005import gc
Antoine Pitrou3024c052017-07-01 19:12:05 +02006import os
Christian Heimes4fbc72b2008-03-22 00:47:35 +00007import pickle
Antoine Pitrou3024c052017-07-01 19:12:05 +02008import random
Christian Heimes4fbc72b2008-03-22 00:47:35 +00009import select
Guido van Rossum4f17e3e1995-03-16 15:07:38 +000010import signal
Victor Stinner11517102014-07-29 23:31:34 +020011import socket
Antoine Pitrou3024c052017-07-01 19:12:05 +020012import statistics
Christian Heimes4fbc72b2008-03-22 00:47:35 +000013import subprocess
14import traceback
Christian Heimesc06950e2008-02-28 21:17:00 +000015import sys, os, time, errno
Berker Peksagce643912015-05-06 06:33:17 +030016from test.support.script_helper import assert_python_ok, spawn_python
Victor Stinnerb3e72192011-05-08 01:46:11 +020017try:
18 import threading
19except ImportError:
20 threading = None
Victor Stinner56e8c292014-07-21 12:30:22 +020021try:
22 import _testcapi
23except ImportError:
24 _testcapi = None
Christian Heimesc06950e2008-02-28 21:17:00 +000025
Guido van Rossumcc5a91d1997-04-16 00:29:15 +000026
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +020027class GenericTests(unittest.TestCase):
28
Stefan Krah63c4b242014-04-15 22:40:06 +020029 @unittest.skipIf(threading is None, "test needs threading module")
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +020030 def test_enums(self):
31 for name in dir(signal):
32 sig = getattr(signal, name)
33 if name in {'SIG_DFL', 'SIG_IGN'}:
34 self.assertIsInstance(sig, signal.Handlers)
35 elif name in {'SIG_BLOCK', 'SIG_UNBLOCK', 'SIG_SETMASK'}:
36 self.assertIsInstance(sig, signal.Sigmasks)
37 elif name.startswith('SIG') and not name.startswith('SIG_'):
38 self.assertIsInstance(sig, signal.Signals)
39 elif name.startswith('CTRL_'):
40 self.assertIsInstance(sig, signal.Signals)
41 self.assertEqual(sys.platform, "win32")
42
43
Brian Curtin3f004b12010-08-06 19:34:52 +000044@unittest.skipIf(sys.platform == "win32", "Not valid on Windows")
Victor Stinnerb3e72192011-05-08 01:46:11 +020045class PosixTests(unittest.TestCase):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000046 def trivial_signal_handler(self, *args):
47 pass
48
Thomas Woutersed03b412007-08-28 21:37:11 +000049 def test_out_of_range_signal_number_raises_error(self):
50 self.assertRaises(ValueError, signal.getsignal, 4242)
51
Thomas Woutersed03b412007-08-28 21:37:11 +000052 self.assertRaises(ValueError, signal.signal, 4242,
Christian Heimes4fbc72b2008-03-22 00:47:35 +000053 self.trivial_signal_handler)
Thomas Woutersed03b412007-08-28 21:37:11 +000054
55 def test_setting_signal_handler_to_none_raises_error(self):
56 self.assertRaises(TypeError, signal.signal,
57 signal.SIGUSR1, None)
58
Christian Heimes4fbc72b2008-03-22 00:47:35 +000059 def test_getsignal(self):
60 hup = signal.signal(signal.SIGHUP, self.trivial_signal_handler)
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +020061 self.assertIsInstance(hup, signal.Handlers)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +000062 self.assertEqual(signal.getsignal(signal.SIGHUP),
63 self.trivial_signal_handler)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000064 signal.signal(signal.SIGHUP, hup)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +000065 self.assertEqual(signal.getsignal(signal.SIGHUP), hup)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000066
Victor Stinner32eb8402016-03-15 11:12:35 +010067 # Issue 3864, unknown if this affects earlier versions of freebsd also
68 @unittest.skipIf(sys.platform=='freebsd6',
69 'inter process signals not reliable (do not mix well with threading) '
70 'on freebsd6')
71 def test_interprocess_signal(self):
72 dirname = os.path.dirname(__file__)
73 script = os.path.join(dirname, 'signalinterproctester.py')
74 assert_python_ok(script)
75
Christian Heimes4fbc72b2008-03-22 00:47:35 +000076
Brian Curtin3f004b12010-08-06 19:34:52 +000077@unittest.skipUnless(sys.platform == "win32", "Windows specific")
78class WindowsSignalTests(unittest.TestCase):
79 def test_issue9324(self):
Brian Curtineccd4d92010-10-01 15:09:53 +000080 # Updated for issue #10003, adding SIGBREAK
Brian Curtin3f004b12010-08-06 19:34:52 +000081 handler = lambda x, y: None
Nick Coghlan60b3ac72013-08-03 22:56:30 +100082 checked = set()
Brian Curtineccd4d92010-10-01 15:09:53 +000083 for sig in (signal.SIGABRT, signal.SIGBREAK, signal.SIGFPE,
84 signal.SIGILL, signal.SIGINT, signal.SIGSEGV,
85 signal.SIGTERM):
Nick Coghlan60b3ac72013-08-03 22:56:30 +100086 # Set and then reset a handler for signals that work on windows.
87 # Issue #18396, only for signals without a C-level handler.
88 if signal.getsignal(sig) is not None:
89 signal.signal(sig, signal.signal(sig, handler))
90 checked.add(sig)
91 # Issue #18396: Ensure the above loop at least tested *something*
92 self.assertTrue(checked)
Brian Curtin3f004b12010-08-06 19:34:52 +000093
94 with self.assertRaises(ValueError):
95 signal.signal(-1, handler)
Brian Curtin80cd4bf2010-08-07 03:52:38 +000096
97 with self.assertRaises(ValueError):
98 signal.signal(7, handler)
Brian Curtin3f004b12010-08-06 19:34:52 +000099
100
Benjamin Petersonc68a4a02013-01-18 00:10:24 -0500101class WakeupFDTests(unittest.TestCase):
102
103 def test_invalid_fd(self):
Victor Stinner1d8948e2014-07-24 22:51:05 +0200104 fd = support.make_bad_fd()
Victor Stinnera7d03d92014-07-21 17:17:28 +0200105 self.assertRaises((ValueError, OSError),
106 signal.set_wakeup_fd, fd)
Benjamin Petersonc68a4a02013-01-18 00:10:24 -0500107
Victor Stinner11517102014-07-29 23:31:34 +0200108 def test_invalid_socket(self):
109 sock = socket.socket()
110 fd = sock.fileno()
111 sock.close()
112 self.assertRaises((ValueError, OSError),
113 signal.set_wakeup_fd, fd)
114
Victor Stinnerd18ccd12014-07-24 21:58:53 +0200115 def test_set_wakeup_fd_result(self):
Victor Stinner1d8948e2014-07-24 22:51:05 +0200116 r1, w1 = os.pipe()
117 self.addCleanup(os.close, r1)
118 self.addCleanup(os.close, w1)
119 r2, w2 = os.pipe()
120 self.addCleanup(os.close, r2)
121 self.addCleanup(os.close, w2)
Victor Stinnerd18ccd12014-07-24 21:58:53 +0200122
Victor Stinner7cea44d2014-08-27 14:02:36 +0200123 if hasattr(os, 'set_blocking'):
124 os.set_blocking(w1, False)
125 os.set_blocking(w2, False)
Victor Stinner38227602014-08-27 12:59:44 +0200126
Victor Stinner1d8948e2014-07-24 22:51:05 +0200127 signal.set_wakeup_fd(w1)
Victor Stinnerc82a1792014-07-24 22:55:12 +0200128 self.assertEqual(signal.set_wakeup_fd(w2), w1)
129 self.assertEqual(signal.set_wakeup_fd(-1), w2)
130 self.assertEqual(signal.set_wakeup_fd(-1), -1)
Victor Stinner56e8c292014-07-21 12:30:22 +0200131
Victor Stinner11517102014-07-29 23:31:34 +0200132 def test_set_wakeup_fd_socket_result(self):
133 sock1 = socket.socket()
134 self.addCleanup(sock1.close)
Victor Stinner38227602014-08-27 12:59:44 +0200135 sock1.setblocking(False)
Victor Stinner11517102014-07-29 23:31:34 +0200136 fd1 = sock1.fileno()
137
138 sock2 = socket.socket()
139 self.addCleanup(sock2.close)
Victor Stinner38227602014-08-27 12:59:44 +0200140 sock2.setblocking(False)
Victor Stinner11517102014-07-29 23:31:34 +0200141 fd2 = sock2.fileno()
142
143 signal.set_wakeup_fd(fd1)
Victor Stinnerda565a72014-07-30 10:03:03 +0200144 self.assertEqual(signal.set_wakeup_fd(fd2), fd1)
145 self.assertEqual(signal.set_wakeup_fd(-1), fd2)
146 self.assertEqual(signal.set_wakeup_fd(-1), -1)
Victor Stinner11517102014-07-29 23:31:34 +0200147
Victor Stinner38227602014-08-27 12:59:44 +0200148 # On Windows, files are always blocking and Windows does not provide a
149 # function to test if a socket is in non-blocking mode.
150 @unittest.skipIf(sys.platform == "win32", "tests specific to POSIX")
151 def test_set_wakeup_fd_blocking(self):
152 rfd, wfd = os.pipe()
153 self.addCleanup(os.close, rfd)
154 self.addCleanup(os.close, wfd)
155
156 # fd must be non-blocking
157 os.set_blocking(wfd, True)
158 with self.assertRaises(ValueError) as cm:
159 signal.set_wakeup_fd(wfd)
160 self.assertEqual(str(cm.exception),
161 "the fd %s must be in non-blocking mode" % wfd)
162
163 # non-blocking is ok
164 os.set_blocking(wfd, False)
165 signal.set_wakeup_fd(wfd)
166 signal.set_wakeup_fd(-1)
167
Benjamin Petersonc68a4a02013-01-18 00:10:24 -0500168
Brian Curtin3f004b12010-08-06 19:34:52 +0000169@unittest.skipIf(sys.platform == "win32", "Not valid on Windows")
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000170class WakeupSignalTests(unittest.TestCase):
Victor Stinner56e8c292014-07-21 12:30:22 +0200171 @unittest.skipIf(_testcapi is None, 'need _testcapi')
Charles-François Natali027f9a32011-10-02 18:36:05 +0200172 def check_wakeup(self, test_body, *signals, ordered=True):
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200173 # use a subprocess to have only one thread
Victor Stinnere40b3aa2011-07-04 17:35:10 +0200174 code = """if 1:
Victor Stinner56e8c292014-07-21 12:30:22 +0200175 import _testcapi
Victor Stinnere40b3aa2011-07-04 17:35:10 +0200176 import os
177 import signal
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200178 import struct
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000179
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200180 signals = {!r}
Victor Stinnerc13ef662011-05-25 02:35:58 +0200181
Victor Stinnere40b3aa2011-07-04 17:35:10 +0200182 def handler(signum, frame):
183 pass
184
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200185 def check_signum(signals):
186 data = os.read(read, len(signals)+1)
187 raised = struct.unpack('%uB' % len(data), data)
Charles-François Natali027f9a32011-10-02 18:36:05 +0200188 if not {!r}:
189 raised = set(raised)
190 signals = set(signals)
Victor Stinner0a01f132011-07-04 18:06:35 +0200191 if raised != signals:
192 raise Exception("%r != %r" % (raised, signals))
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200193
Victor Stinnere40b3aa2011-07-04 17:35:10 +0200194 {}
195
196 signal.signal(signal.SIGALRM, handler)
197 read, write = os.pipe()
Victor Stinner1db9e7b2014-07-29 22:32:47 +0200198 os.set_blocking(write, False)
Victor Stinnere40b3aa2011-07-04 17:35:10 +0200199 signal.set_wakeup_fd(write)
200
201 test()
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200202 check_signum(signals)
Victor Stinnere40b3aa2011-07-04 17:35:10 +0200203
204 os.close(read)
205 os.close(write)
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +0200206 """.format(tuple(map(int, signals)), ordered, test_body)
Victor Stinnere40b3aa2011-07-04 17:35:10 +0200207
208 assert_python_ok('-c', code)
Victor Stinnerd49b1f12011-05-08 02:03:15 +0200209
Victor Stinner56e8c292014-07-21 12:30:22 +0200210 @unittest.skipIf(_testcapi is None, 'need _testcapi')
Antoine Pitrou6f6ec372013-08-17 20:27:56 +0200211 def test_wakeup_write_error(self):
212 # Issue #16105: write() errors in the C signal handler should not
213 # pass silently.
214 # Use a subprocess to have only one thread.
215 code = """if 1:
Victor Stinner56e8c292014-07-21 12:30:22 +0200216 import _testcapi
Antoine Pitrou6f6ec372013-08-17 20:27:56 +0200217 import errno
Antoine Pitrou6f6ec372013-08-17 20:27:56 +0200218 import os
219 import signal
220 import sys
Antoine Pitrou6f6ec372013-08-17 20:27:56 +0200221 from test.support import captured_stderr
222
223 def handler(signum, frame):
224 1/0
225
226 signal.signal(signal.SIGALRM, handler)
227 r, w = os.pipe()
Victor Stinner1db9e7b2014-07-29 22:32:47 +0200228 os.set_blocking(r, False)
Antoine Pitrou6f6ec372013-08-17 20:27:56 +0200229
230 # Set wakeup_fd a read-only file descriptor to trigger the error
231 signal.set_wakeup_fd(r)
232 try:
233 with captured_stderr() as err:
Victor Stinner56e8c292014-07-21 12:30:22 +0200234 _testcapi.raise_signal(signal.SIGALRM)
Antoine Pitrou6f6ec372013-08-17 20:27:56 +0200235 except ZeroDivisionError:
236 # An ignored exception should have been printed out on stderr
237 err = err.getvalue()
238 if ('Exception ignored when trying to write to the signal wakeup fd'
239 not in err):
240 raise AssertionError(err)
241 if ('OSError: [Errno %d]' % errno.EBADF) not in err:
242 raise AssertionError(err)
243 else:
244 raise AssertionError("ZeroDivisionError not raised")
Victor Stinner56e8c292014-07-21 12:30:22 +0200245
246 os.close(r)
247 os.close(w)
Antoine Pitrou6f6ec372013-08-17 20:27:56 +0200248 """
Antoine Pitrou8f0bdda2013-08-17 21:43:47 +0200249 r, w = os.pipe()
250 try:
251 os.write(r, b'x')
252 except OSError:
253 pass
254 else:
255 self.skipTest("OS doesn't report write() error on the read end of a pipe")
256 finally:
257 os.close(r)
258 os.close(w)
Antoine Pitrou6f6ec372013-08-17 20:27:56 +0200259
260 assert_python_ok('-c', code)
261
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000262 def test_wakeup_fd_early(self):
Victor Stinnere40b3aa2011-07-04 17:35:10 +0200263 self.check_wakeup("""def test():
264 import select
265 import time
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000266
Victor Stinnere40b3aa2011-07-04 17:35:10 +0200267 TIMEOUT_FULL = 10
268 TIMEOUT_HALF = 5
269
Victor Stinner749a6a82015-03-30 22:09:14 +0200270 class InterruptSelect(Exception):
271 pass
272
273 def handler(signum, frame):
274 raise InterruptSelect
275 signal.signal(signal.SIGALRM, handler)
276
Victor Stinnere40b3aa2011-07-04 17:35:10 +0200277 signal.alarm(1)
Victor Stinner79d68f92015-03-19 21:54:09 +0100278
Victor Stinnere40b3aa2011-07-04 17:35:10 +0200279 # We attempt to get a signal during the sleep,
280 # before select is called
Victor Stinner79d68f92015-03-19 21:54:09 +0100281 try:
282 select.select([], [], [], TIMEOUT_FULL)
Victor Stinner749a6a82015-03-30 22:09:14 +0200283 except InterruptSelect:
Victor Stinner79d68f92015-03-19 21:54:09 +0100284 pass
285 else:
286 raise Exception("select() was not interrupted")
287
288 before_time = time.monotonic()
Victor Stinnere40b3aa2011-07-04 17:35:10 +0200289 select.select([read], [], [], TIMEOUT_FULL)
Victor Stinner79d68f92015-03-19 21:54:09 +0100290 after_time = time.monotonic()
291 dt = after_time - before_time
Victor Stinner0a01f132011-07-04 18:06:35 +0200292 if dt >= TIMEOUT_HALF:
293 raise Exception("%s >= %s" % (dt, TIMEOUT_HALF))
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200294 """, signal.SIGALRM)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000295
296 def test_wakeup_fd_during(self):
Victor Stinnere40b3aa2011-07-04 17:35:10 +0200297 self.check_wakeup("""def test():
298 import select
299 import time
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000300
Victor Stinnere40b3aa2011-07-04 17:35:10 +0200301 TIMEOUT_FULL = 10
302 TIMEOUT_HALF = 5
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000303
Victor Stinner749a6a82015-03-30 22:09:14 +0200304 class InterruptSelect(Exception):
305 pass
306
307 def handler(signum, frame):
308 raise InterruptSelect
309 signal.signal(signal.SIGALRM, handler)
310
Victor Stinnere40b3aa2011-07-04 17:35:10 +0200311 signal.alarm(1)
Victor Stinner79d68f92015-03-19 21:54:09 +0100312 before_time = time.monotonic()
Victor Stinnere40b3aa2011-07-04 17:35:10 +0200313 # We attempt to get a signal during the select call
314 try:
315 select.select([read], [], [], TIMEOUT_FULL)
Victor Stinner749a6a82015-03-30 22:09:14 +0200316 except InterruptSelect:
Victor Stinnere40b3aa2011-07-04 17:35:10 +0200317 pass
318 else:
Victor Stinner749a6a82015-03-30 22:09:14 +0200319 raise Exception("select() was not interrupted")
Victor Stinner79d68f92015-03-19 21:54:09 +0100320 after_time = time.monotonic()
Victor Stinnere40b3aa2011-07-04 17:35:10 +0200321 dt = after_time - before_time
Victor Stinner0a01f132011-07-04 18:06:35 +0200322 if dt >= TIMEOUT_HALF:
323 raise Exception("%s >= %s" % (dt, TIMEOUT_HALF))
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200324 """, signal.SIGALRM)
Victor Stinnerd49b1f12011-05-08 02:03:15 +0200325
326 def test_signum(self):
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200327 self.check_wakeup("""def test():
Victor Stinner56e8c292014-07-21 12:30:22 +0200328 import _testcapi
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200329 signal.signal(signal.SIGUSR1, handler)
Victor Stinner56e8c292014-07-21 12:30:22 +0200330 _testcapi.raise_signal(signal.SIGUSR1)
331 _testcapi.raise_signal(signal.SIGALRM)
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200332 """, signal.SIGUSR1, signal.SIGALRM)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000333
Victor Stinnerc13ef662011-05-25 02:35:58 +0200334 @unittest.skipUnless(hasattr(signal, 'pthread_sigmask'),
335 'need signal.pthread_sigmask()')
Victor Stinnerc13ef662011-05-25 02:35:58 +0200336 def test_pending(self):
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200337 self.check_wakeup("""def test():
338 signum1 = signal.SIGUSR1
339 signum2 = signal.SIGUSR2
Victor Stinnerc13ef662011-05-25 02:35:58 +0200340
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200341 signal.signal(signum1, handler)
342 signal.signal(signum2, handler)
Victor Stinnerc13ef662011-05-25 02:35:58 +0200343
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200344 signal.pthread_sigmask(signal.SIG_BLOCK, (signum1, signum2))
Victor Stinner56e8c292014-07-21 12:30:22 +0200345 _testcapi.raise_signal(signum1)
346 _testcapi.raise_signal(signum2)
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200347 # Unblocking the 2 signals calls the C signal handler twice
348 signal.pthread_sigmask(signal.SIG_UNBLOCK, (signum1, signum2))
Charles-François Natali027f9a32011-10-02 18:36:05 +0200349 """, signal.SIGUSR1, signal.SIGUSR2, ordered=False)
Victor Stinnerc13ef662011-05-25 02:35:58 +0200350
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000351
Victor Stinner11517102014-07-29 23:31:34 +0200352@unittest.skipUnless(hasattr(socket, 'socketpair'), 'need socket.socketpair')
353class WakeupSocketSignalTests(unittest.TestCase):
354
355 @unittest.skipIf(_testcapi is None, 'need _testcapi')
356 def test_socket(self):
357 # use a subprocess to have only one thread
358 code = """if 1:
359 import signal
360 import socket
361 import struct
362 import _testcapi
363
364 signum = signal.SIGINT
365 signals = (signum,)
366
367 def handler(signum, frame):
368 pass
369
370 signal.signal(signum, handler)
371
372 read, write = socket.socketpair()
373 read.setblocking(False)
374 write.setblocking(False)
375 signal.set_wakeup_fd(write.fileno())
376
377 _testcapi.raise_signal(signum)
378
379 data = read.recv(1)
380 if not data:
381 raise Exception("no signum written")
382 raised = struct.unpack('B', data)
383 if raised != signals:
384 raise Exception("%r != %r" % (raised, signals))
385
386 read.close()
387 write.close()
388 """
389
390 assert_python_ok('-c', code)
391
392 @unittest.skipIf(_testcapi is None, 'need _testcapi')
393 def test_send_error(self):
394 # Use a subprocess to have only one thread.
395 if os.name == 'nt':
396 action = 'send'
397 else:
398 action = 'write'
399 code = """if 1:
400 import errno
401 import signal
402 import socket
403 import sys
404 import time
405 import _testcapi
406 from test.support import captured_stderr
407
408 signum = signal.SIGINT
409
410 def handler(signum, frame):
411 pass
412
413 signal.signal(signum, handler)
414
415 read, write = socket.socketpair()
416 read.setblocking(False)
417 write.setblocking(False)
418
419 signal.set_wakeup_fd(write.fileno())
420
421 # Close sockets: send() will fail
422 read.close()
423 write.close()
424
425 with captured_stderr() as err:
426 _testcapi.raise_signal(signum)
427
428 err = err.getvalue()
429 if ('Exception ignored when trying to {action} to the signal wakeup fd'
430 not in err):
431 raise AssertionError(err)
432 """.format(action=action)
433 assert_python_ok('-c', code)
434
435
Brian Curtin3f004b12010-08-06 19:34:52 +0000436@unittest.skipIf(sys.platform == "win32", "Not valid on Windows")
Christian Heimes8640e742008-02-23 16:23:06 +0000437class SiginterruptTest(unittest.TestCase):
Jean-Paul Calderone9c39bc72010-05-09 03:25:16 +0000438
Victor Stinnerd6284962011-06-20 23:28:09 +0200439 def readpipe_interrupted(self, interrupt):
Jean-Paul Calderone9c39bc72010-05-09 03:25:16 +0000440 """Perform a read during which a signal will arrive. Return True if the
441 read is interrupted by the signal and raises an exception. Return False
442 if it returns normally.
443 """
Victor Stinnerd6284962011-06-20 23:28:09 +0200444 # use a subprocess to have only one thread, to have a timeout on the
445 # blocking read and to not touch signal handling in this process
446 code = """if 1:
447 import errno
448 import os
449 import signal
450 import sys
Jean-Paul Calderone9c39bc72010-05-09 03:25:16 +0000451
Victor Stinnerd6284962011-06-20 23:28:09 +0200452 interrupt = %r
453 r, w = os.pipe()
Christian Heimes8640e742008-02-23 16:23:06 +0000454
Victor Stinnerd6284962011-06-20 23:28:09 +0200455 def handler(signum, frame):
Charles-François Natali6e6c59b2015-02-07 13:27:50 +0000456 1 / 0
Victor Stinnerd6284962011-06-20 23:28:09 +0200457
458 signal.signal(signal.SIGALRM, handler)
459 if interrupt is not None:
460 signal.siginterrupt(signal.SIGALRM, interrupt)
461
Victor Stinnerdfde0d42011-07-01 15:58:39 +0200462 print("ready")
463 sys.stdout.flush()
464
Victor Stinnerd6284962011-06-20 23:28:09 +0200465 # run the test twice
Victor Stinner56e8c292014-07-21 12:30:22 +0200466 try:
467 for loop in range(2):
468 # send a SIGALRM in a second (during the read)
469 signal.alarm(1)
470 try:
471 # blocking call: read from a pipe without data
472 os.read(r, 1)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +0000473 except ZeroDivisionError:
474 pass
Victor Stinner56e8c292014-07-21 12:30:22 +0200475 else:
476 sys.exit(2)
477 sys.exit(3)
478 finally:
479 os.close(r)
480 os.close(w)
Victor Stinnerd6284962011-06-20 23:28:09 +0200481 """ % (interrupt,)
482 with spawn_python('-c', code) as process:
Christian Heimes8640e742008-02-23 16:23:06 +0000483 try:
Victor Stinner45273652011-06-22 22:15:51 +0200484 # wait until the child process is loaded and has started
485 first_line = process.stdout.readline()
486
Victor Stinner19e5bcd2011-07-01 15:59:54 +0200487 stdout, stderr = process.communicate(timeout=5.0)
Victor Stinnerd6284962011-06-20 23:28:09 +0200488 except subprocess.TimeoutExpired:
489 process.kill()
Christian Heimes8640e742008-02-23 16:23:06 +0000490 return False
Victor Stinnerd6284962011-06-20 23:28:09 +0200491 else:
Victor Stinner45273652011-06-22 22:15:51 +0200492 stdout = first_line + stdout
Victor Stinnerd6284962011-06-20 23:28:09 +0200493 exitcode = process.wait()
494 if exitcode not in (2, 3):
Antoine Pitroudab4e8a2014-05-11 19:05:23 +0200495 raise Exception("Child error (exit code %s): %r"
Victor Stinnerd6284962011-06-20 23:28:09 +0200496 % (exitcode, stdout))
497 return (exitcode == 3)
Christian Heimes8640e742008-02-23 16:23:06 +0000498
499 def test_without_siginterrupt(self):
Victor Stinner3a7f0f02011-05-08 02:10:36 +0200500 # If a signal handler is installed and siginterrupt is not called
501 # at all, when that signal arrives, it interrupts a syscall that's in
502 # progress.
Victor Stinnerd6284962011-06-20 23:28:09 +0200503 interrupted = self.readpipe_interrupted(None)
504 self.assertTrue(interrupted)
Christian Heimes8640e742008-02-23 16:23:06 +0000505
506 def test_siginterrupt_on(self):
Victor Stinner3a7f0f02011-05-08 02:10:36 +0200507 # If a signal handler is installed and siginterrupt is called with
508 # a true value for the second argument, when that signal arrives, it
509 # interrupts a syscall that's in progress.
Victor Stinnerd6284962011-06-20 23:28:09 +0200510 interrupted = self.readpipe_interrupted(True)
511 self.assertTrue(interrupted)
Christian Heimes8640e742008-02-23 16:23:06 +0000512
513 def test_siginterrupt_off(self):
Victor Stinner3a7f0f02011-05-08 02:10:36 +0200514 # If a signal handler is installed and siginterrupt is called with
515 # a false value for the second argument, when that signal arrives, it
516 # does not interrupt a syscall that's in progress.
Victor Stinnerd6284962011-06-20 23:28:09 +0200517 interrupted = self.readpipe_interrupted(False)
518 self.assertFalse(interrupted)
Jean-Paul Calderone9c39bc72010-05-09 03:25:16 +0000519
520
Brian Curtin3f004b12010-08-06 19:34:52 +0000521@unittest.skipIf(sys.platform == "win32", "Not valid on Windows")
Martin v. Löwis823725e2008-03-24 13:39:54 +0000522class ItimerTest(unittest.TestCase):
523 def setUp(self):
524 self.hndl_called = False
525 self.hndl_count = 0
526 self.itimer = None
Christian Heimescc47b052008-03-25 14:56:36 +0000527 self.old_alarm = signal.signal(signal.SIGALRM, self.sig_alrm)
Martin v. Löwis823725e2008-03-24 13:39:54 +0000528
529 def tearDown(self):
Christian Heimescc47b052008-03-25 14:56:36 +0000530 signal.signal(signal.SIGALRM, self.old_alarm)
Martin v. Löwis823725e2008-03-24 13:39:54 +0000531 if self.itimer is not None: # test_itimer_exc doesn't change this attr
532 # just ensure that itimer is stopped
533 signal.setitimer(self.itimer, 0)
534
535 def sig_alrm(self, *args):
536 self.hndl_called = True
Martin v. Löwis823725e2008-03-24 13:39:54 +0000537
538 def sig_vtalrm(self, *args):
539 self.hndl_called = True
540
541 if self.hndl_count > 3:
542 # it shouldn't be here, because it should have been disabled.
543 raise signal.ItimerError("setitimer didn't disable ITIMER_VIRTUAL "
544 "timer.")
545 elif self.hndl_count == 3:
546 # disable ITIMER_VIRTUAL, this function shouldn't be called anymore
547 signal.setitimer(signal.ITIMER_VIRTUAL, 0)
Martin v. Löwis823725e2008-03-24 13:39:54 +0000548
549 self.hndl_count += 1
550
Martin v. Löwis823725e2008-03-24 13:39:54 +0000551 def sig_prof(self, *args):
552 self.hndl_called = True
553 signal.setitimer(signal.ITIMER_PROF, 0)
554
Martin v. Löwis823725e2008-03-24 13:39:54 +0000555 def test_itimer_exc(self):
556 # XXX I'm assuming -1 is an invalid itimer, but maybe some platform
557 # defines it ?
558 self.assertRaises(signal.ItimerError, signal.setitimer, -1, 0)
Christian Heimescc47b052008-03-25 14:56:36 +0000559 # Negative times are treated as zero on some platforms.
560 if 0:
561 self.assertRaises(signal.ItimerError,
562 signal.setitimer, signal.ITIMER_REAL, -1)
Martin v. Löwis823725e2008-03-24 13:39:54 +0000563
564 def test_itimer_real(self):
565 self.itimer = signal.ITIMER_REAL
Martin v. Löwis823725e2008-03-24 13:39:54 +0000566 signal.setitimer(self.itimer, 1.0)
Martin v. Löwis823725e2008-03-24 13:39:54 +0000567 signal.pause()
Martin v. Löwis823725e2008-03-24 13:39:54 +0000568 self.assertEqual(self.hndl_called, True)
569
R. David Murray44546f82010-04-21 01:59:28 +0000570 # Issue 3864, unknown if this affects earlier versions of freebsd also
Gregory P. Smith397cd8a2010-10-17 04:23:21 +0000571 @unittest.skipIf(sys.platform in ('freebsd6', 'netbsd5'),
572 'itimer not reliable (does not mix well with threading) on some BSDs.')
Martin v. Löwis823725e2008-03-24 13:39:54 +0000573 def test_itimer_virtual(self):
574 self.itimer = signal.ITIMER_VIRTUAL
575 signal.signal(signal.SIGVTALRM, self.sig_vtalrm)
576 signal.setitimer(self.itimer, 0.3, 0.2)
577
Victor Stinner79d68f92015-03-19 21:54:09 +0100578 start_time = time.monotonic()
579 while time.monotonic() - start_time < 60.0:
Mark Dickinson95078872009-10-04 18:47:48 +0000580 # use up some virtual time by doing real work
581 _ = pow(12345, 67890, 10000019)
Martin v. Löwis823725e2008-03-24 13:39:54 +0000582 if signal.getitimer(self.itimer) == (0.0, 0.0):
583 break # sig_vtalrm handler stopped this itimer
Stefan Krahf1da973042010-04-20 08:15:14 +0000584 else: # Issue 8424
Benjamin Peterson9b140f62010-05-15 18:00:56 +0000585 self.skipTest("timeout: likely cause: machine too slow or load too "
586 "high")
Martin v. Löwis823725e2008-03-24 13:39:54 +0000587
588 # virtual itimer should be (0.0, 0.0) now
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000589 self.assertEqual(signal.getitimer(self.itimer), (0.0, 0.0))
Martin v. Löwis823725e2008-03-24 13:39:54 +0000590 # and the handler should have been called
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000591 self.assertEqual(self.hndl_called, True)
Martin v. Löwis823725e2008-03-24 13:39:54 +0000592
R. David Murray44546f82010-04-21 01:59:28 +0000593 # Issue 3864, unknown if this affects earlier versions of freebsd also
594 @unittest.skipIf(sys.platform=='freebsd6',
595 'itimer not reliable (does not mix well with threading) on freebsd6')
Martin v. Löwis823725e2008-03-24 13:39:54 +0000596 def test_itimer_prof(self):
597 self.itimer = signal.ITIMER_PROF
598 signal.signal(signal.SIGPROF, self.sig_prof)
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000599 signal.setitimer(self.itimer, 0.2, 0.2)
Martin v. Löwis823725e2008-03-24 13:39:54 +0000600
Victor Stinner79d68f92015-03-19 21:54:09 +0100601 start_time = time.monotonic()
602 while time.monotonic() - start_time < 60.0:
Mark Dickinson78373472009-10-31 10:39:21 +0000603 # do some work
604 _ = pow(12345, 67890, 10000019)
Martin v. Löwis823725e2008-03-24 13:39:54 +0000605 if signal.getitimer(self.itimer) == (0.0, 0.0):
606 break # sig_prof handler stopped this itimer
Stefan Krahf1da973042010-04-20 08:15:14 +0000607 else: # Issue 8424
Benjamin Peterson9b140f62010-05-15 18:00:56 +0000608 self.skipTest("timeout: likely cause: machine too slow or load too "
609 "high")
Martin v. Löwis823725e2008-03-24 13:39:54 +0000610
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000611 # profiling itimer should be (0.0, 0.0) now
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000612 self.assertEqual(signal.getitimer(self.itimer), (0.0, 0.0))
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000613 # and the handler should have been called
Martin v. Löwis823725e2008-03-24 13:39:54 +0000614 self.assertEqual(self.hndl_called, True)
615
Antoine Pitrou6f3cb052017-06-30 10:54:24 +0200616 def test_setitimer_tiny(self):
617 # bpo-30807: C setitimer() takes a microsecond-resolution interval.
618 # Check that float -> timeval conversion doesn't round
619 # the interval down to zero, which would disable the timer.
620 self.itimer = signal.ITIMER_REAL
621 signal.setitimer(self.itimer, 1e-6)
622 time.sleep(1)
623 self.assertEqual(self.hndl_called, True)
624
Victor Stinnera9293352011-04-30 15:21:58 +0200625
Victor Stinner35b300c2011-05-04 13:20:35 +0200626class PendingSignalsTests(unittest.TestCase):
627 """
Victor Stinnerb3e72192011-05-08 01:46:11 +0200628 Test pthread_sigmask(), pthread_kill(), sigpending() and sigwait()
629 functions.
Victor Stinner35b300c2011-05-04 13:20:35 +0200630 """
Victor Stinnerb3e72192011-05-08 01:46:11 +0200631 @unittest.skipUnless(hasattr(signal, 'sigpending'),
632 'need signal.sigpending()')
633 def test_sigpending_empty(self):
634 self.assertEqual(signal.sigpending(), set())
635
636 @unittest.skipUnless(hasattr(signal, 'pthread_sigmask'),
637 'need signal.pthread_sigmask()')
638 @unittest.skipUnless(hasattr(signal, 'sigpending'),
639 'need signal.sigpending()')
640 def test_sigpending(self):
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200641 code = """if 1:
642 import os
643 import signal
Victor Stinnerb3e72192011-05-08 01:46:11 +0200644
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200645 def handler(signum, frame):
646 1/0
Victor Stinnerb3e72192011-05-08 01:46:11 +0200647
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200648 signum = signal.SIGUSR1
649 signal.signal(signum, handler)
650
651 signal.pthread_sigmask(signal.SIG_BLOCK, [signum])
652 os.kill(os.getpid(), signum)
653 pending = signal.sigpending()
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +0200654 for sig in pending:
655 assert isinstance(sig, signal.Signals), repr(pending)
Victor Stinner0a01f132011-07-04 18:06:35 +0200656 if pending != {signum}:
657 raise Exception('%s != {%s}' % (pending, signum))
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200658 try:
659 signal.pthread_sigmask(signal.SIG_UNBLOCK, [signum])
660 except ZeroDivisionError:
661 pass
662 else:
663 raise Exception("ZeroDivisionError not raised")
664 """
665 assert_python_ok('-c', code)
Victor Stinnerb3e72192011-05-08 01:46:11 +0200666
667 @unittest.skipUnless(hasattr(signal, 'pthread_kill'),
668 'need signal.pthread_kill()')
669 def test_pthread_kill(self):
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200670 code = """if 1:
671 import signal
672 import threading
673 import sys
Victor Stinnerb3e72192011-05-08 01:46:11 +0200674
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200675 signum = signal.SIGUSR1
Victor Stinnerb3e72192011-05-08 01:46:11 +0200676
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200677 def handler(signum, frame):
678 1/0
679
680 signal.signal(signum, handler)
681
682 if sys.platform == 'freebsd6':
683 # Issue #12392 and #12469: send a signal to the main thread
684 # doesn't work before the creation of the first thread on
685 # FreeBSD 6
686 def noop():
687 pass
688 thread = threading.Thread(target=noop)
689 thread.start()
690 thread.join()
691
692 tid = threading.get_ident()
693 try:
694 signal.pthread_kill(tid, signum)
695 except ZeroDivisionError:
696 pass
697 else:
698 raise Exception("ZeroDivisionError not raised")
699 """
700 assert_python_ok('-c', code)
Victor Stinnerb3e72192011-05-08 01:46:11 +0200701
Victor Stinner7f294d12011-06-10 14:02:10 +0200702 @unittest.skipUnless(hasattr(signal, 'pthread_sigmask'),
703 'need signal.pthread_sigmask()')
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200704 def wait_helper(self, blocked, test):
Victor Stinner9e8b82f2011-06-29 10:43:02 +0200705 """
706 test: body of the "def test(signum):" function.
707 blocked: number of the blocked signal
708 """
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200709 code = '''if 1:
710 import signal
711 import sys
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +0200712 from signal import Signals
Victor Stinner9e8b82f2011-06-29 10:43:02 +0200713
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200714 def handler(signum, frame):
715 1/0
Victor Stinner9e8b82f2011-06-29 10:43:02 +0200716
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200717 %s
Victor Stinner9e8b82f2011-06-29 10:43:02 +0200718
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200719 blocked = %s
720 signum = signal.SIGALRM
Victor Stinner9e8b82f2011-06-29 10:43:02 +0200721
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200722 # child: block and wait the signal
723 try:
724 signal.signal(signum, handler)
725 signal.pthread_sigmask(signal.SIG_BLOCK, [blocked])
Victor Stinner9e8b82f2011-06-29 10:43:02 +0200726
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200727 # Do the tests
728 test(signum)
Victor Stinner9e8b82f2011-06-29 10:43:02 +0200729
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200730 # The handler must not be called on unblock
731 try:
732 signal.pthread_sigmask(signal.SIG_UNBLOCK, [blocked])
733 except ZeroDivisionError:
734 print("the signal handler has been called",
735 file=sys.stderr)
736 sys.exit(1)
737 except BaseException as err:
738 print("error: {}".format(err), file=sys.stderr)
739 sys.stderr.flush()
740 sys.exit(1)
741 ''' % (test.strip(), blocked)
Victor Stinner415007e2011-06-13 16:19:06 +0200742
Ross Lagerwallbc808222011-06-25 12:13:40 +0200743 # sig*wait* must be called with the signal blocked: since the current
Victor Stinner9e8b82f2011-06-29 10:43:02 +0200744 # process might have several threads running, use a subprocess to have
745 # a single thread.
746 assert_python_ok('-c', code)
Victor Stinneraf494602011-06-10 12:48:13 +0200747
Victor Stinnerb3e72192011-05-08 01:46:11 +0200748 @unittest.skipUnless(hasattr(signal, 'sigwait'),
749 'need signal.sigwait()')
Ross Lagerwallbc808222011-06-25 12:13:40 +0200750 def test_sigwait(self):
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200751 self.wait_helper(signal.SIGALRM, '''
752 def test(signum):
Ross Lagerwallbc808222011-06-25 12:13:40 +0200753 signal.alarm(1)
Victor Stinner9e8b82f2011-06-29 10:43:02 +0200754 received = signal.sigwait([signum])
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +0200755 assert isinstance(received, signal.Signals), received
Victor Stinner0a01f132011-07-04 18:06:35 +0200756 if received != signum:
757 raise Exception('received %s, not %s' % (received, signum))
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200758 ''')
Ross Lagerwallbc808222011-06-25 12:13:40 +0200759
760 @unittest.skipUnless(hasattr(signal, 'sigwaitinfo'),
761 'need signal.sigwaitinfo()')
762 def test_sigwaitinfo(self):
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200763 self.wait_helper(signal.SIGALRM, '''
764 def test(signum):
Ross Lagerwallbc808222011-06-25 12:13:40 +0200765 signal.alarm(1)
766 info = signal.sigwaitinfo([signum])
Victor Stinner0a01f132011-07-04 18:06:35 +0200767 if info.si_signo != signum:
768 raise Exception("info.si_signo != %s" % signum)
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200769 ''')
Ross Lagerwallbc808222011-06-25 12:13:40 +0200770
771 @unittest.skipUnless(hasattr(signal, 'sigtimedwait'),
772 'need signal.sigtimedwait()')
773 def test_sigtimedwait(self):
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200774 self.wait_helper(signal.SIGALRM, '''
775 def test(signum):
Ross Lagerwallbc808222011-06-25 12:13:40 +0200776 signal.alarm(1)
Victor Stinner643cd682012-03-02 22:54:03 +0100777 info = signal.sigtimedwait([signum], 10.1000)
Victor Stinner0a01f132011-07-04 18:06:35 +0200778 if info.si_signo != signum:
779 raise Exception('info.si_signo != %s' % signum)
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200780 ''')
Ross Lagerwallbc808222011-06-25 12:13:40 +0200781
Ross Lagerwallbc808222011-06-25 12:13:40 +0200782 @unittest.skipUnless(hasattr(signal, 'sigtimedwait'),
783 'need signal.sigtimedwait()')
784 def test_sigtimedwait_poll(self):
Victor Stinner9e8b82f2011-06-29 10:43:02 +0200785 # check that polling with sigtimedwait works
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200786 self.wait_helper(signal.SIGALRM, '''
787 def test(signum):
Victor Stinner9e8b82f2011-06-29 10:43:02 +0200788 import os
789 os.kill(os.getpid(), signum)
Victor Stinner643cd682012-03-02 22:54:03 +0100790 info = signal.sigtimedwait([signum], 0)
Victor Stinner0a01f132011-07-04 18:06:35 +0200791 if info.si_signo != signum:
792 raise Exception('info.si_signo != %s' % signum)
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200793 ''')
Ross Lagerwallbc808222011-06-25 12:13:40 +0200794
795 @unittest.skipUnless(hasattr(signal, 'sigtimedwait'),
796 'need signal.sigtimedwait()')
797 def test_sigtimedwait_timeout(self):
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200798 self.wait_helper(signal.SIGALRM, '''
799 def test(signum):
Victor Stinner643cd682012-03-02 22:54:03 +0100800 received = signal.sigtimedwait([signum], 1.0)
Victor Stinner0a01f132011-07-04 18:06:35 +0200801 if received is not None:
802 raise Exception("received=%r" % (received,))
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200803 ''')
Ross Lagerwallbc808222011-06-25 12:13:40 +0200804
805 @unittest.skipUnless(hasattr(signal, 'sigtimedwait'),
806 'need signal.sigtimedwait()')
807 def test_sigtimedwait_negative_timeout(self):
808 signum = signal.SIGALRM
Victor Stinner643cd682012-03-02 22:54:03 +0100809 self.assertRaises(ValueError, signal.sigtimedwait, [signum], -1.0)
Ross Lagerwallbc808222011-06-25 12:13:40 +0200810
Ross Lagerwallbc808222011-06-25 12:13:40 +0200811 @unittest.skipUnless(hasattr(signal, 'sigwait'),
812 'need signal.sigwait()')
Victor Stinner415007e2011-06-13 16:19:06 +0200813 @unittest.skipUnless(hasattr(signal, 'pthread_sigmask'),
814 'need signal.pthread_sigmask()')
Victor Stinner10c30d62011-06-10 01:39:53 +0200815 @unittest.skipIf(threading is None, "test needs threading module")
816 def test_sigwait_thread(self):
Victor Stinner415007e2011-06-13 16:19:06 +0200817 # Check that calling sigwait() from a thread doesn't suspend the whole
818 # process. A new interpreter is spawned to avoid problems when mixing
819 # threads and fork(): only async-safe functions are allowed between
820 # fork() and exec().
821 assert_python_ok("-c", """if True:
822 import os, threading, sys, time, signal
Victor Stinner10c30d62011-06-10 01:39:53 +0200823
Victor Stinner415007e2011-06-13 16:19:06 +0200824 # the default handler terminates the process
825 signum = signal.SIGUSR1
826
827 def kill_later():
828 # wait until the main thread is waiting in sigwait()
829 time.sleep(1)
830 os.kill(os.getpid(), signum)
831
832 # the signal must be blocked by all the threads
833 signal.pthread_sigmask(signal.SIG_BLOCK, [signum])
834 killer = threading.Thread(target=kill_later)
Victor Stinneraf494602011-06-10 12:48:13 +0200835 killer.start()
836 received = signal.sigwait([signum])
837 if received != signum:
838 print("sigwait() received %s, not %s" % (received, signum),
839 file=sys.stderr)
Victor Stinner415007e2011-06-13 16:19:06 +0200840 sys.exit(1)
Victor Stinner10c30d62011-06-10 01:39:53 +0200841 killer.join()
Victor Stinner415007e2011-06-13 16:19:06 +0200842 # unblock the signal, which should have been cleared by sigwait()
843 signal.pthread_sigmask(signal.SIG_UNBLOCK, [signum])
844 """)
Victor Stinneraf494602011-06-10 12:48:13 +0200845
Victor Stinnerb3e72192011-05-08 01:46:11 +0200846 @unittest.skipUnless(hasattr(signal, 'pthread_sigmask'),
847 'need signal.pthread_sigmask()')
848 def test_pthread_sigmask_arguments(self):
849 self.assertRaises(TypeError, signal.pthread_sigmask)
850 self.assertRaises(TypeError, signal.pthread_sigmask, 1)
851 self.assertRaises(TypeError, signal.pthread_sigmask, 1, 2, 3)
852 self.assertRaises(OSError, signal.pthread_sigmask, 1700, [])
853
854 @unittest.skipUnless(hasattr(signal, 'pthread_sigmask'),
855 'need signal.pthread_sigmask()')
856 def test_pthread_sigmask(self):
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200857 code = """if 1:
858 import signal
859 import os; import threading
860
861 def handler(signum, frame):
862 1/0
863
864 def kill(signum):
865 os.kill(os.getpid(), signum)
866
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +0200867 def check_mask(mask):
868 for sig in mask:
869 assert isinstance(sig, signal.Signals), repr(sig)
870
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200871 def read_sigmask():
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +0200872 sigmask = signal.pthread_sigmask(signal.SIG_BLOCK, [])
873 check_mask(sigmask)
874 return sigmask
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200875
Victor Stinnerb3e72192011-05-08 01:46:11 +0200876 signum = signal.SIGUSR1
Victor Stinner6fd49e12011-05-04 12:38:03 +0200877
Victor Stinnerd0e516d2011-05-03 14:57:12 +0200878 # Install our signal handler
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200879 old_handler = signal.signal(signum, handler)
Victor Stinnera9293352011-04-30 15:21:58 +0200880
Victor Stinnerd0e516d2011-05-03 14:57:12 +0200881 # Unblock SIGUSR1 (and copy the old mask) to test our signal handler
Victor Stinnera9293352011-04-30 15:21:58 +0200882 old_mask = signal.pthread_sigmask(signal.SIG_UNBLOCK, [signum])
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +0200883 check_mask(old_mask)
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200884 try:
885 kill(signum)
886 except ZeroDivisionError:
887 pass
888 else:
889 raise Exception("ZeroDivisionError not raised")
Victor Stinnera9293352011-04-30 15:21:58 +0200890
Victor Stinnerd0e516d2011-05-03 14:57:12 +0200891 # Block and then raise SIGUSR1. The signal is blocked: the signal
892 # handler is not called, and the signal is now pending
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +0200893 mask = signal.pthread_sigmask(signal.SIG_BLOCK, [signum])
894 check_mask(mask)
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200895 kill(signum)
Victor Stinnera9293352011-04-30 15:21:58 +0200896
Victor Stinnerd0e516d2011-05-03 14:57:12 +0200897 # Check the new mask
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200898 blocked = read_sigmask()
Giampaolo Rodola'e09fb712014-04-04 15:34:17 +0200899 check_mask(blocked)
Victor Stinner0a01f132011-07-04 18:06:35 +0200900 if signum not in blocked:
901 raise Exception("%s not in %s" % (signum, blocked))
902 if old_mask ^ blocked != {signum}:
903 raise Exception("%s ^ %s != {%s}" % (old_mask, blocked, signum))
Victor Stinnera9293352011-04-30 15:21:58 +0200904
Victor Stinnerd0e516d2011-05-03 14:57:12 +0200905 # Unblock SIGUSR1
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200906 try:
R David Murrayfc069992013-12-13 20:52:19 -0500907 # unblock the pending signal calls immediately the signal handler
Victor Stinnerd0e516d2011-05-03 14:57:12 +0200908 signal.pthread_sigmask(signal.SIG_UNBLOCK, [signum])
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200909 except ZeroDivisionError:
910 pass
911 else:
912 raise Exception("ZeroDivisionError not raised")
913 try:
914 kill(signum)
915 except ZeroDivisionError:
916 pass
917 else:
918 raise Exception("ZeroDivisionError not raised")
Victor Stinnera9293352011-04-30 15:21:58 +0200919
Victor Stinnerd0e516d2011-05-03 14:57:12 +0200920 # Check the new mask
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200921 unblocked = read_sigmask()
Victor Stinner0a01f132011-07-04 18:06:35 +0200922 if signum in unblocked:
923 raise Exception("%s in %s" % (signum, unblocked))
924 if blocked ^ unblocked != {signum}:
925 raise Exception("%s ^ %s != {%s}" % (blocked, unblocked, signum))
926 if old_mask != unblocked:
927 raise Exception("%s != %s" % (old_mask, unblocked))
Victor Stinnerd554cdf2011-07-04 17:49:40 +0200928 """
929 assert_python_ok('-c', code)
930
931 @unittest.skipIf(sys.platform == 'freebsd6',
932 "issue #12392: send a signal to the main thread doesn't work "
933 "before the creation of the first thread on FreeBSD 6")
934 @unittest.skipUnless(hasattr(signal, 'pthread_kill'),
935 'need signal.pthread_kill()')
936 def test_pthread_kill_main_thread(self):
937 # Test that a signal can be sent to the main thread with pthread_kill()
938 # before any other thread has been created (see issue #12392).
939 code = """if True:
940 import threading
941 import signal
942 import sys
943
944 def handler(signum, frame):
945 sys.exit(3)
946
947 signal.signal(signal.SIGUSR1, handler)
948 signal.pthread_kill(threading.get_ident(), signal.SIGUSR1)
949 sys.exit(2)
950 """
951
952 with spawn_python('-c', code) as process:
953 stdout, stderr = process.communicate()
954 exitcode = process.wait()
955 if exitcode != 3:
956 raise Exception("Child error (exit code %s): %s" %
957 (exitcode, stdout))
Victor Stinnera9293352011-04-30 15:21:58 +0200958
959
Antoine Pitrou3024c052017-07-01 19:12:05 +0200960class StressTest(unittest.TestCase):
961 """
962 Stress signal delivery, especially when a signal arrives in
963 the middle of recomputing the signal state or executing
964 previously tripped signal handlers.
965 """
966
967 def setsig(self, signum, handler):
968 old_handler = signal.signal(signum, handler)
969 self.addCleanup(signal.signal, signum, old_handler)
970
971 def measure_itimer_resolution(self):
972 N = 20
973 times = []
974
975 def handler(signum=None, frame=None):
976 if len(times) < N:
977 times.append(time.perf_counter())
978 # 1 µs is the smallest possible timer interval,
979 # we want to measure what the concrete duration
980 # will be on this platform
981 signal.setitimer(signal.ITIMER_REAL, 1e-6)
982
983 self.addCleanup(signal.setitimer, signal.ITIMER_REAL, 0)
984 self.setsig(signal.SIGALRM, handler)
985 handler()
986 while len(times) < N:
987 time.sleep(1e-3)
988
989 durations = [times[i+1] - times[i] for i in range(len(times) - 1)]
990 med = statistics.median(durations)
991 if support.verbose:
992 print("detected median itimer() resolution: %.6f s." % (med,))
993 return med
994
995 def decide_itimer_count(self):
996 # Some systems have poor setitimer() resolution (for example
997 # measured around 20 ms. on FreeBSD 9), so decide on a reasonable
998 # number of sequential timers based on that.
999 reso = self.measure_itimer_resolution()
1000 if reso <= 1e-4:
1001 return 10000
1002 elif reso <= 1e-2:
1003 return 100
1004 else:
1005 self.skipTest("detected itimer resolution (%.3f s.) too high "
1006 "(> 10 ms.) on this platform (or system too busy)"
1007 % (reso,))
1008
1009 @unittest.skipUnless(hasattr(signal, "setitimer"),
1010 "test needs setitimer()")
1011 def test_stress_delivery_dependent(self):
1012 """
1013 This test uses dependent signal handlers.
1014 """
1015 N = self.decide_itimer_count()
1016 sigs = []
1017
1018 def first_handler(signum, frame):
1019 # 1e-6 is the minimum non-zero value for `setitimer()`.
1020 # Choose a random delay so as to improve chances of
1021 # triggering a race condition. Ideally the signal is received
1022 # when inside critical signal-handling routines such as
1023 # Py_MakePendingCalls().
1024 signal.setitimer(signal.ITIMER_REAL, 1e-6 + random.random() * 1e-5)
1025
1026 def second_handler(signum=None, frame=None):
1027 sigs.append(signum)
1028
1029 # Here on Linux, SIGPROF > SIGALRM > SIGUSR1. By using both
1030 # ascending and descending sequences (SIGUSR1 then SIGALRM,
1031 # SIGPROF then SIGALRM), we maximize chances of hitting a bug.
1032 self.setsig(signal.SIGPROF, first_handler)
1033 self.setsig(signal.SIGUSR1, first_handler)
1034 self.setsig(signal.SIGALRM, second_handler) # for ITIMER_REAL
1035
1036 expected_sigs = 0
1037 deadline = time.time() + 15.0
1038
1039 while expected_sigs < N:
1040 os.kill(os.getpid(), signal.SIGPROF)
1041 expected_sigs += 1
1042 # Wait for handlers to run to avoid signal coalescing
1043 while len(sigs) < expected_sigs and time.time() < deadline:
1044 time.sleep(1e-5)
1045
1046 os.kill(os.getpid(), signal.SIGUSR1)
1047 expected_sigs += 1
1048 while len(sigs) < expected_sigs and time.time() < deadline:
1049 time.sleep(1e-5)
1050
1051 # All ITIMER_REAL signals should have been delivered to the
1052 # Python handler
1053 self.assertEqual(len(sigs), N, "Some signals were lost")
1054
1055 @unittest.skipUnless(hasattr(signal, "setitimer"),
1056 "test needs setitimer()")
1057 def test_stress_delivery_simultaneous(self):
1058 """
1059 This test uses simultaneous signal handlers.
1060 """
1061 N = self.decide_itimer_count()
1062 sigs = []
1063
1064 def handler(signum, frame):
1065 sigs.append(signum)
1066
1067 self.setsig(signal.SIGUSR1, handler)
1068 self.setsig(signal.SIGALRM, handler) # for ITIMER_REAL
1069
1070 expected_sigs = 0
1071 deadline = time.time() + 15.0
1072
1073 while expected_sigs < N:
1074 # Hopefully the SIGALRM will be received somewhere during
1075 # initial processing of SIGUSR1.
1076 signal.setitimer(signal.ITIMER_REAL, 1e-6 + random.random() * 1e-5)
1077 os.kill(os.getpid(), signal.SIGUSR1)
1078
1079 expected_sigs += 2
1080 # Wait for handlers to run to avoid signal coalescing
1081 while len(sigs) < expected_sigs and time.time() < deadline:
1082 time.sleep(1e-5)
1083
1084 # All ITIMER_REAL signals should have been delivered to the
1085 # Python handler
1086 self.assertEqual(len(sigs), N, "Some signals were lost")
1087
1088
Zachary Ware38c707e2015-04-13 15:00:43 -05001089def tearDownModule():
1090 support.reap_children()
Thomas Woutersed03b412007-08-28 21:37:11 +00001091
1092if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -05001093 unittest.main()