Debian Codegraph @

Lib/test/test_signal.py

raw
1 import enum
2 import errno
3 import functools
4 import inspect
5 import os
6 import random
7 import signal
8 import socket
9 import statistics
10 import subprocess
11 import sys
12 import threading
13 import time
14 import unittest
15 from test import support
16 from test.support import (
17 is_apple, is_apple_mobile, os_helper, threading_helper
18 )
19 from test.support.script_helper import assert_python_ok, spawn_python
20 try:
21 import _testcapi
22 except ImportError:
23 _testcapi = None
24
25
26 class GenericTests(unittest.TestCase):
27
28 def test_enums(self):
29 for name in dir(signal):
30 sig = getattr(signal, name)
31 if name in {'SIG_DFL', 'SIG_IGN'}:
32 self.assertIsInstance(sig, signal.Handlers)
33 elif name in {'SIG_BLOCK', 'SIG_UNBLOCK', 'SIG_SETMASK'}:
34 self.assertIsInstance(sig, signal.Sigmasks)
35 elif name.startswith('SIG') and not name.startswith('SIG_'):
36 self.assertIsInstance(sig, signal.Signals)
37 elif name.startswith('CTRL_'):
38 self.assertIsInstance(sig, signal.Signals)
39 self.assertEqual(sys.platform, "win32")
40
41 CheckedSignals = enum._old_convert_(
42 enum.IntEnum, 'Signals', 'signal',
43 lambda name:
44 name.isupper()
45 and (name.startswith('SIG') and not name.startswith('SIG_'))
46 or name.startswith('CTRL_'),
47 source=signal,
48 )
49 enum._test_simple_enum(CheckedSignals, signal.Signals)
50
51 CheckedHandlers = enum._old_convert_(
52 enum.IntEnum, 'Handlers', 'signal',
53 lambda name: name in ('SIG_DFL', 'SIG_IGN'),
54 source=signal,
55 )
56 enum._test_simple_enum(CheckedHandlers, signal.Handlers)
57
58 Sigmasks = getattr(signal, 'Sigmasks', None)
59 if Sigmasks is not None:
60 CheckedSigmasks = enum._old_convert_(
61 enum.IntEnum, 'Sigmasks', 'signal',
62 lambda name: name in ('SIG_BLOCK', 'SIG_UNBLOCK', 'SIG_SETMASK'),
63 source=signal,
64 )
65 enum._test_simple_enum(CheckedSigmasks, Sigmasks)
66
67 def test_functions_module_attr(self):
68 # Issue #27718: If __all__ is not defined all non-builtin functions
69 # should have correct __module__ to be displayed by pydoc.
70 for name in dir(signal):
71 value = getattr(signal, name)
72 if inspect.isroutine(value) and not inspect.isbuiltin(value):
73 self.assertEqual(value.__module__, 'signal')
74
75
76 @unittest.skipIf(sys.platform == "win32", "Not valid on Windows")
77 class PosixTests(unittest.TestCase):
78 def trivial_signal_handler(self, *args):
79 pass
80
81 def create_handler_with_partial(self, argument):
82 return functools.partial(self.trivial_signal_handler, argument)
83
84 def test_out_of_range_signal_number_raises_error(self):
85 self.assertRaises(ValueError, signal.getsignal, 4242)
86
87 self.assertRaises(ValueError, signal.signal, 4242,
88 self.trivial_signal_handler)
89
90 self.assertRaises(ValueError, signal.strsignal, 4242)
91
92 def test_setting_signal_handler_to_none_raises_error(self):
93 self.assertRaises(TypeError, signal.signal,
94 signal.SIGUSR1, None)
95
96 def test_getsignal(self):
97 hup = signal.signal(signal.SIGHUP, self.trivial_signal_handler)
98 self.assertIsInstance(hup, signal.Handlers)
99 self.assertEqual(signal.getsignal(signal.SIGHUP),
100 self.trivial_signal_handler)
101 signal.signal(signal.SIGHUP, hup)
102 self.assertEqual(signal.getsignal(signal.SIGHUP), hup)
103
104 def test_no_repr_is_called_on_signal_handler(self):
105 # See https://github.com/python/cpython/issues/112559.
106
107 class MyArgument:
108 def __init__(self):
109 self.repr_count = 0
110
111 def __repr__(self):
112 self.repr_count += 1
113 return super().__repr__()
114
115 argument = MyArgument()
116 self.assertEqual(0, argument.repr_count)
117
118 handler = self.create_handler_with_partial(argument)
119 hup = signal.signal(signal.SIGHUP, handler)
120 self.assertIsInstance(hup, signal.Handlers)
121 self.assertEqual(signal.getsignal(signal.SIGHUP), handler)
122 signal.signal(signal.SIGHUP, hup)
123 self.assertEqual(signal.getsignal(signal.SIGHUP), hup)
124 self.assertEqual(0, argument.repr_count)
125
126 @unittest.skipIf(sys.platform.startswith("netbsd"),
127 "gh-124083: strsignal is not supported on NetBSD")
128 def test_strsignal(self):
129 self.assertIn("Interrupt", signal.strsignal(signal.SIGINT))
130 self.assertIn("Terminated", signal.strsignal(signal.SIGTERM))
131 self.assertIn("Hangup", signal.strsignal(signal.SIGHUP))
132
133 # Issue 3864, unknown if this affects earlier versions of freebsd also
134 def test_interprocess_signal(self):
135 dirname = os.path.dirname(__file__)
136 script = os.path.join(dirname, 'signalinterproctester.py')
137 assert_python_ok(script)
138
139 @unittest.skipUnless(
140 hasattr(signal, "valid_signals"),
141 "requires signal.valid_signals"
142 )
143 def test_valid_signals(self):
144 s = signal.valid_signals()
145 self.assertIsInstance(s, set)
146 self.assertIn(signal.Signals.SIGINT, s)
147 self.assertIn(signal.Signals.SIGALRM, s)
148 self.assertNotIn(0, s)
149 self.assertNotIn(signal.NSIG, s)
150 self.assertLess(len(s), signal.NSIG)
151
152 # gh-91145: Make sure that all SIGxxx constants exposed by the Python
153 # signal module have a number in the [0; signal.NSIG-1] range.
154 for name in dir(signal):
155 if not name.startswith("SIG"):
156 continue
157 if name in {"SIG_IGN", "SIG_DFL"}:
158 # SIG_IGN and SIG_DFL are pointers
159 continue
160 with self.subTest(name=name):
161 signum = getattr(signal, name)
162 self.assertGreaterEqual(signum, 0)
163 self.assertLess(signum, signal.NSIG)
164
165 @unittest.skipUnless(sys.executable, "sys.executable required.")
166 @support.requires_subprocess()
167 def test_keyboard_interrupt_exit_code(self):
168 """KeyboardInterrupt triggers exit via SIGINT."""
169 process = subprocess.run(
170 [sys.executable, "-c",
171 "import os, signal, time\n"
172 "os.kill(os.getpid(), signal.SIGINT)\n"
173 "for _ in range(999): time.sleep(0.01)"],
174 stderr=subprocess.PIPE)
175 self.assertIn(b"KeyboardInterrupt", process.stderr)
176 self.assertEqual(process.returncode, -signal.SIGINT)
177 # Caveat: The exit code is insufficient to guarantee we actually died
178 # via a signal. POSIX shells do more than look at the 8 bit value.
179 # Writing an automation friendly test of an interactive shell
180 # to confirm that our process died via a SIGINT proved too complex.
181
182
183 @unittest.skipUnless(sys.platform == "win32", "Windows specific")
184 class WindowsSignalTests(unittest.TestCase):
185
186 def test_valid_signals(self):
187 s = signal.valid_signals()
188 self.assertIsInstance(s, set)
189 self.assertGreaterEqual(len(s), 6)
190 self.assertIn(signal.Signals.SIGINT, s)
191 self.assertNotIn(0, s)
192 self.assertNotIn(signal.NSIG, s)
193 self.assertLess(len(s), signal.NSIG)
194
195 def test_issue9324(self):
196 # Updated for issue #10003, adding SIGBREAK
197 handler = lambda x, y: None
198 checked = set()
199 for sig in (signal.SIGABRT, signal.SIGBREAK, signal.SIGFPE,
200 signal.SIGILL, signal.SIGINT, signal.SIGSEGV,
201 signal.SIGTERM):
202 # Set and then reset a handler for signals that work on windows.
203 # Issue #18396, only for signals without a C-level handler.
204 if signal.getsignal(sig) is not None:
205 signal.signal(sig, signal.signal(sig, handler))
206 checked.add(sig)
207 # Issue #18396: Ensure the above loop at least tested *something*
208 self.assertTrue(checked)
209
210 with self.assertRaises(ValueError):
211 signal.signal(-1, handler)
212
213 with self.assertRaises(ValueError):
214 signal.signal(7, handler)
215
216 @unittest.skipUnless(sys.executable, "sys.executable required.")
217 @support.requires_subprocess()
218 def test_keyboard_interrupt_exit_code(self):
219 """KeyboardInterrupt triggers an exit using STATUS_CONTROL_C_EXIT."""
220 # We don't test via os.kill(os.getpid(), signal.CTRL_C_EVENT) here
221 # as that requires setting up a console control handler in a child
222 # in its own process group. Doable, but quite complicated. (see
223 # @eryksun on https://github.com/python/cpython/pull/11862)
224 process = subprocess.run(
225 [sys.executable, "-c", "raise KeyboardInterrupt"],
226 stderr=subprocess.PIPE)
227 self.assertIn(b"KeyboardInterrupt", process.stderr)
228 STATUS_CONTROL_C_EXIT = 0xC000013A
229 self.assertEqual(process.returncode, STATUS_CONTROL_C_EXIT)
230
231
232 class WakeupFDTests(unittest.TestCase):
233
234 def test_invalid_call(self):
235 # First parameter is positional-only
236 with self.assertRaises(TypeError):
237 signal.set_wakeup_fd(signum=signal.SIGINT)
238
239 # warn_on_full_buffer is a keyword-only parameter
240 with self.assertRaises(TypeError):
241 signal.set_wakeup_fd(signal.SIGINT, False)
242
243 def test_invalid_fd(self):
244 fd = os_helper.make_bad_fd()
245 self.assertRaises((ValueError, OSError),
246 signal.set_wakeup_fd, fd)
247
248 @unittest.skipUnless(support.has_socket_support, "needs working sockets.")
249 def test_invalid_socket(self):
250 sock = socket.socket()
251 fd = sock.fileno()
252 sock.close()
253 self.assertRaises((ValueError, OSError),
254 signal.set_wakeup_fd, fd)
255
256 @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
257 def test_set_wakeup_fd_result(self):
258 r1, w1 = os.pipe()
259 self.addCleanup(os.close, r1)
260 self.addCleanup(os.close, w1)
261 r2, w2 = os.pipe()
262 self.addCleanup(os.close, r2)
263 self.addCleanup(os.close, w2)
264
265 if hasattr(os, 'set_blocking'):
266 os.set_blocking(w1, False)
267 os.set_blocking(w2, False)
268
269 signal.set_wakeup_fd(w1)
270 self.assertEqual(signal.set_wakeup_fd(w2), w1)
271 self.assertEqual(signal.set_wakeup_fd(-1), w2)
272 self.assertEqual(signal.set_wakeup_fd(-1), -1)
273
274 @unittest.skipUnless(support.has_socket_support, "needs working sockets.")
275 def test_set_wakeup_fd_socket_result(self):
276 sock1 = socket.socket()
277 self.addCleanup(sock1.close)
278 sock1.setblocking(False)
279 fd1 = sock1.fileno()
280
281 sock2 = socket.socket()
282 self.addCleanup(sock2.close)
283 sock2.setblocking(False)
284 fd2 = sock2.fileno()
285
286 signal.set_wakeup_fd(fd1)
287 self.assertEqual(signal.set_wakeup_fd(fd2), fd1)
288 self.assertEqual(signal.set_wakeup_fd(-1), fd2)
289 self.assertEqual(signal.set_wakeup_fd(-1), -1)
290
291 # On Windows, files are always blocking and Windows does not provide a
292 # function to test if a socket is in non-blocking mode.
293 @unittest.skipIf(sys.platform == "win32", "tests specific to POSIX")
294 @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
295 def test_set_wakeup_fd_blocking(self):
296 rfd, wfd = os.pipe()
297 self.addCleanup(os.close, rfd)
298 self.addCleanup(os.close, wfd)
299
300 # fd must be non-blocking
301 os.set_blocking(wfd, True)
302 with self.assertRaises(ValueError) as cm:
303 signal.set_wakeup_fd(wfd)
304 self.assertEqual(str(cm.exception),
305 "the fd %s must be in non-blocking mode" % wfd)
306
307 # non-blocking is ok
308 os.set_blocking(wfd, False)
309 signal.set_wakeup_fd(wfd)
310 signal.set_wakeup_fd(-1)
311
312
313 @unittest.skipIf(sys.platform == "win32", "Not valid on Windows")
314 class WakeupSignalTests(unittest.TestCase):
315 @unittest.skipIf(_testcapi is None, 'need _testcapi')
316 def check_wakeup(self, test_body, *signals, ordered=True):
317 # use a subprocess to have only one thread
318 code = """if 1:
319 import _testcapi
320 import os
321 import signal
322 import struct
323
324 signals = {!r}
325
326 def handler(signum, frame):
327 pass
328
329 def check_signum(signals):
330 data = os.read(read, len(signals)+1)
331 raised = struct.unpack('%uB' % len(data), data)
332 if not {!r}:
333 raised = set(raised)
334 signals = set(signals)
335 if raised != signals:
336 raise Exception("%r != %r" % (raised, signals))
337
338 {}
339
340 signal.signal(signal.SIGALRM, handler)
341 read, write = os.pipe()
342 os.set_blocking(write, False)
343 signal.set_wakeup_fd(write)
344
345 test()
346 check_signum(signals)
347
348 os.close(read)
349 os.close(write)
350 """.format(tuple(map(int, signals)), ordered, test_body)
351
352 assert_python_ok('-c', code)
353
354 @unittest.skipIf(_testcapi is None, 'need _testcapi')
355 @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
356 def test_wakeup_write_error(self):
357 # Issue #16105: write() errors in the C signal handler should not
358 # pass silently.
359 # Use a subprocess to have only one thread.
360 code = """if 1:
361 import _testcapi
362 import errno
363 import os
364 import signal
365 import sys
366 from test.support import captured_stderr
367
368 def handler(signum, frame):
369 1/0
370
371 signal.signal(signal.SIGALRM, handler)
372 r, w = os.pipe()
373 os.set_blocking(r, False)
374
375 # Set wakeup_fd a read-only file descriptor to trigger the error
376 signal.set_wakeup_fd(r)
377 try:
378 with captured_stderr() as err:
379 signal.raise_signal(signal.SIGALRM)
380 except ZeroDivisionError:
381 # An ignored exception should have been printed out on stderr
382 err = err.getvalue()
383 if ('Exception ignored while trying to write to the signal wakeup fd'
384 not in err):
385 raise AssertionError(err)
386 if ('OSError: [Errno %d]' % errno.EBADF) not in err:
387 raise AssertionError(err)
388 else:
389 raise AssertionError("ZeroDivisionError not raised")
390
391 os.close(r)
392 os.close(w)
393 """
394 r, w = os.pipe()
395 try:
396 os.write(r, b'x')
397 except OSError:
398 pass
399 else:
400 self.skipTest("OS doesn't report write() error on the read end of a pipe")
401 finally:
402 os.close(r)
403 os.close(w)
404
405 assert_python_ok('-c', code)
406
407 def test_wakeup_fd_early(self):
408 self.check_wakeup("""def test():
409 import select
410 import time
411
412 TIMEOUT_FULL = 10
413 TIMEOUT_HALF = 5
414
415 class InterruptSelect(Exception):
416 pass
417
418 def handler(signum, frame):
419 raise InterruptSelect
420 signal.signal(signal.SIGALRM, handler)
421
422 signal.alarm(1)
423
424 # We attempt to get a signal during the sleep,
425 # before select is called
426 try:
427 select.select([], [], [], TIMEOUT_FULL)
428 except InterruptSelect:
429 pass
430 else:
431 raise Exception("select() was not interrupted")
432
433 before_time = time.monotonic()
434 select.select([read], [], [], TIMEOUT_FULL)
435 after_time = time.monotonic()
436 dt = after_time - before_time
437 if dt >= TIMEOUT_HALF:
438 raise Exception("%s >= %s" % (dt, TIMEOUT_HALF))
439 """, signal.SIGALRM)
440
441 def test_wakeup_fd_during(self):
442 self.check_wakeup("""def test():
443 import select
444 import time
445
446 TIMEOUT_FULL = 10
447 TIMEOUT_HALF = 5
448
449 class InterruptSelect(Exception):
450 pass
451
452 def handler(signum, frame):
453 raise InterruptSelect
454 signal.signal(signal.SIGALRM, handler)
455
456 signal.alarm(1)
457 before_time = time.monotonic()
458 # We attempt to get a signal during the select call
459 try:
460 select.select([read], [], [], TIMEOUT_FULL)
461 except InterruptSelect:
462 pass
463 else:
464 raise Exception("select() was not interrupted")
465 after_time = time.monotonic()
466 dt = after_time - before_time
467 if dt >= TIMEOUT_HALF:
468 raise Exception("%s >= %s" % (dt, TIMEOUT_HALF))
469 """, signal.SIGALRM)
470
471 def test_signum(self):
472 self.check_wakeup("""def test():
473 signal.signal(signal.SIGUSR1, handler)
474 signal.raise_signal(signal.SIGUSR1)
475 signal.raise_signal(signal.SIGALRM)
476 """, signal.SIGUSR1, signal.SIGALRM)
477
478 @unittest.skipUnless(hasattr(signal, 'pthread_sigmask'),
479 'need signal.pthread_sigmask()')
480 def test_pending(self):
481 self.check_wakeup("""def test():
482 signum1 = signal.SIGUSR1
483 signum2 = signal.SIGUSR2
484
485 signal.signal(signum1, handler)
486 signal.signal(signum2, handler)
487
488 signal.pthread_sigmask(signal.SIG_BLOCK, (signum1, signum2))
489 signal.raise_signal(signum1)
490 signal.raise_signal(signum2)
491 # Unblocking the 2 signals calls the C signal handler twice
492 signal.pthread_sigmask(signal.SIG_UNBLOCK, (signum1, signum2))
493 """, signal.SIGUSR1, signal.SIGUSR2, ordered=False)
494
495
496 @unittest.skipUnless(hasattr(socket, 'socketpair'), 'need socket.socketpair')
497 class WakeupSocketSignalTests(unittest.TestCase):
498
499 @unittest.skipIf(_testcapi is None, 'need _testcapi')
500 def test_socket(self):
501 # use a subprocess to have only one thread
502 code = """if 1:
503 import signal
504 import socket
505 import struct
506 import _testcapi
507
508 signum = signal.SIGINT
509 signals = (signum,)
510
511 def handler(signum, frame):
512 pass
513
514 signal.signal(signum, handler)
515
516 read, write = socket.socketpair()
517 write.setblocking(False)
518 signal.set_wakeup_fd(write.fileno())
519
520 signal.raise_signal(signum)
521
522 data = read.recv(1)
523 if not data:
524 raise Exception("no signum written")
525 raised = struct.unpack('B', data)
526 if raised != signals:
527 raise Exception("%r != %r" % (raised, signals))
528
529 read.close()
530 write.close()
531 """
532
533 assert_python_ok('-c', code)
534
535 @unittest.skipIf(_testcapi is None, 'need _testcapi')
536 def test_send_error(self):
537 # Use a subprocess to have only one thread.
538 if os.name == 'nt':
539 action = 'send'
540 else:
541 action = 'write'
542 code = """if 1:
543 import errno
544 import signal
545 import socket
546 import sys
547 import time
548 import _testcapi
549 from test.support import captured_stderr
550
551 signum = signal.SIGINT
552
553 def handler(signum, frame):
554 pass
555
556 signal.signal(signum, handler)
557
558 read, write = socket.socketpair()
559 read.setblocking(False)
560 write.setblocking(False)
561
562 signal.set_wakeup_fd(write.fileno())
563
564 # Close sockets: send() will fail
565 read.close()
566 write.close()
567
568 with captured_stderr() as err:
569 signal.raise_signal(signum)
570
571 err = err.getvalue()
572 if ('Exception ignored while trying to {action} to the signal wakeup fd'
573 not in err):
574 raise AssertionError(err)
575 """.format(action=action)
576 assert_python_ok('-c', code)
577
578 @unittest.skipIf(_testcapi is None, 'need _testcapi')
579 def test_warn_on_full_buffer(self):
580 # Use a subprocess to have only one thread.
581 if os.name == 'nt':
582 action = 'send'
583 else:
584 action = 'write'
585 code = """if 1:
586 import errno
587 import signal
588 import socket
589 import sys
590 import time
591 import _testcapi
592 from test.support import captured_stderr
593
594 signum = signal.SIGINT
595
596 # This handler will be called, but we intentionally won't read from
597 # the wakeup fd.
598 def handler(signum, frame):
599 pass
600
601 signal.signal(signum, handler)
602
603 read, write = socket.socketpair()
604
605 # Fill the socketpair buffer
606 if sys.platform == 'win32':
607 # bpo-34130: On Windows, sometimes non-blocking send fails to fill
608 # the full socketpair buffer, so use a timeout of 50 ms instead.
609 write.settimeout(0.050)
610 else:
611 write.setblocking(False)
612
613 written = 0
614 if sys.platform == "vxworks":
615 CHUNK_SIZES = (1,)
616 else:
617 # Start with large chunk size to reduce the
618 # number of send needed to fill the buffer.
619 CHUNK_SIZES = (2 ** 16, 2 ** 8, 1)
620 for chunk_size in CHUNK_SIZES:
621 chunk = b"x" * chunk_size
622 try:
623 while True:
624 write.send(chunk)
625 written += chunk_size
626 except (BlockingIOError, TimeoutError):
627 pass
628
629 print(f"%s bytes written into the socketpair" % written, flush=True)
630
631 write.setblocking(False)
632 try:
633 write.send(b"x")
634 except BlockingIOError:
635 # The socketpair buffer seems full
636 pass
637 else:
638 raise AssertionError("%s bytes failed to fill the socketpair "
639 "buffer" % written)
640
641 # By default, we get a warning when a signal arrives
642 msg = ('Exception ignored while trying to {action} '
643 'to the signal wakeup fd')
644 signal.set_wakeup_fd(write.fileno())
645
646 with captured_stderr() as err:
647 signal.raise_signal(signum)
648
649 err = err.getvalue()
650 if msg not in err:
651 raise AssertionError("first set_wakeup_fd() test failed, "
652 "stderr: %r" % err)
653
654 # And also if warn_on_full_buffer=True
655 signal.set_wakeup_fd(write.fileno(), warn_on_full_buffer=True)
656
657 with captured_stderr() as err:
658 signal.raise_signal(signum)
659
660 err = err.getvalue()
661 if msg not in err:
662 raise AssertionError("set_wakeup_fd(warn_on_full_buffer=True) "
663 "test failed, stderr: %r" % err)
664
665 # But not if warn_on_full_buffer=False
666 signal.set_wakeup_fd(write.fileno(), warn_on_full_buffer=False)
667
668 with captured_stderr() as err:
669 signal.raise_signal(signum)
670
671 err = err.getvalue()
672 if err != "":
673 raise AssertionError("set_wakeup_fd(warn_on_full_buffer=False) "
674 "test failed, stderr: %r" % err)
675
676 # And then check the default again, to make sure warn_on_full_buffer
677 # settings don't leak across calls.
678 signal.set_wakeup_fd(write.fileno())
679
680 with captured_stderr() as err:
681 signal.raise_signal(signum)
682
683 err = err.getvalue()
684 if msg not in err:
685 raise AssertionError("second set_wakeup_fd() test failed, "
686 "stderr: %r" % err)
687
688 """.format(action=action)
689 assert_python_ok('-c', code)
690
691
692 @unittest.skipIf(sys.platform == "win32", "Not valid on Windows")
693 @unittest.skipUnless(hasattr(signal, 'siginterrupt'), "needs signal.siginterrupt()")
694 @support.requires_subprocess()
695 @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
696 class SiginterruptTest(unittest.TestCase):
697
698 def readpipe_interrupted(self, interrupt, timeout=support.SHORT_TIMEOUT):
699 """Perform a read during which a signal will arrive. Return True if the
700 read is interrupted by the signal and raises an exception. Return False
701 if it returns normally.
702 """
703 # use a subprocess to have only one thread, to have a timeout on the
704 # blocking read and to not touch signal handling in this process
705 code = """if 1:
706 import errno
707 import os
708 import signal
709 import sys
710
711 interrupt = %r
712 r, w = os.pipe()
713
714 def handler(signum, frame):
715 1 / 0
716
717 signal.signal(signal.SIGALRM, handler)
718 if interrupt is not None:
719 signal.siginterrupt(signal.SIGALRM, interrupt)
720
721 print("ready")
722 sys.stdout.flush()
723
724 # run the test twice
725 try:
726 for loop in range(2):
727 # send a SIGALRM in a second (during the read)
728 signal.alarm(1)
729 try:
730 # blocking call: read from a pipe without data
731 os.read(r, 1)
732 except ZeroDivisionError:
733 pass
734 else:
735 sys.exit(2)
736 sys.exit(3)
737 finally:
738 os.close(r)
739 os.close(w)
740 """ % (interrupt,)
741 with spawn_python('-c', code) as process:
742 try:
743 # wait until the child process is loaded and has started
744 first_line = process.stdout.readline()
745
746 stdout, stderr = process.communicate(timeout=timeout)
747 except subprocess.TimeoutExpired:
748 process.kill()
749 return False
750 else:
751 stdout = first_line + stdout
752 exitcode = process.wait()
753 if exitcode not in (2, 3):
754 raise Exception("Child error (exit code %s): %r"
755 % (exitcode, stdout))
756 return (exitcode == 3)
757
758 def test_without_siginterrupt(self):
759 # If a signal handler is installed and siginterrupt is not called
760 # at all, when that signal arrives, it interrupts a syscall that's in
761 # progress.
762 interrupted = self.readpipe_interrupted(None)
763 self.assertTrue(interrupted)
764
765 def test_siginterrupt_on(self):
766 # If a signal handler is installed and siginterrupt is called with
767 # a true value for the second argument, when that signal arrives, it
768 # interrupts a syscall that's in progress.
769 interrupted = self.readpipe_interrupted(True)
770 self.assertTrue(interrupted)
771
772 @support.requires_resource('walltime')
773 def test_siginterrupt_off(self):
774 # If a signal handler is installed and siginterrupt is called with
775 # a false value for the second argument, when that signal arrives, it
776 # does not interrupt a syscall that's in progress.
777 interrupted = self.readpipe_interrupted(False, timeout=2)
778 self.assertFalse(interrupted)
779
780
781 @unittest.skipIf(sys.platform == "win32", "Not valid on Windows")
782 @unittest.skipUnless(hasattr(signal, 'getitimer') and hasattr(signal, 'setitimer'),
783 "needs signal.getitimer() and signal.setitimer()")
784 class ItimerTest(unittest.TestCase):
785 def setUp(self):
786 self.hndl_called = False
787 self.hndl_count = 0
788 self.itimer = None
789 self.old_alarm = signal.signal(signal.SIGALRM, self.sig_alrm)
790
791 def tearDown(self):
792 signal.signal(signal.SIGALRM, self.old_alarm)
793 if self.itimer is not None: # test_itimer_exc doesn't change this attr
794 # just ensure that itimer is stopped
795 signal.setitimer(self.itimer, 0)
796
797 def sig_alrm(self, *args):
798 self.hndl_called = True
799
800 def sig_vtalrm(self, *args):
801 self.hndl_called = True
802
803 if self.hndl_count > 3:
804 # it shouldn't be here, because it should have been disabled.
805 raise signal.ItimerError("setitimer didn't disable ITIMER_VIRTUAL "
806 "timer.")
807 elif self.hndl_count == 3:
808 # disable ITIMER_VIRTUAL, this function shouldn't be called anymore
809 signal.setitimer(signal.ITIMER_VIRTUAL, 0)
810
811 self.hndl_count += 1
812
813 def sig_prof(self, *args):
814 self.hndl_called = True
815 signal.setitimer(signal.ITIMER_PROF, 0)
816
817 def test_itimer_exc(self):
818 # XXX I'm assuming -1 is an invalid itimer, but maybe some platform
819 # defines it ?
820 self.assertRaises(signal.ItimerError, signal.setitimer, -1, 0)
821 # Negative times are treated as zero on some platforms.
822 if 0:
823 self.assertRaises(signal.ItimerError,
824 signal.setitimer, signal.ITIMER_REAL, -1)
825
826 def test_itimer_real(self):
827 self.itimer = signal.ITIMER_REAL
828 signal.setitimer(self.itimer, 1.0)
829 signal.pause()
830 self.assertEqual(self.hndl_called, True)
831
832 # Issue 3864, unknown if this affects earlier versions of freebsd also
833 @unittest.skipIf(sys.platform in ('netbsd5',) or is_apple_mobile,
834 'itimer not reliable (does not mix well with threading) on some BSDs.')
835 def test_itimer_virtual(self):
836 self.itimer = signal.ITIMER_VIRTUAL
837 signal.signal(signal.SIGVTALRM, self.sig_vtalrm)
838 signal.setitimer(self.itimer, 0.001, 0.001)
839
840 for _ in support.busy_retry(support.LONG_TIMEOUT):
841 # use up some virtual time by doing real work
842 _ = sum(i * i for i in range(10**5))
843 if signal.getitimer(self.itimer) == (0.0, 0.0):
844 # sig_vtalrm handler stopped this itimer
845 break
846
847 # virtual itimer should be (0.0, 0.0) now
848 self.assertEqual(signal.getitimer(self.itimer), (0.0, 0.0))
849 # and the handler should have been called
850 self.assertEqual(self.hndl_called, True)
851
852 def test_itimer_prof(self):
853 self.itimer = signal.ITIMER_PROF
854 signal.signal(signal.SIGPROF, self.sig_prof)
855 signal.setitimer(self.itimer, 0.2, 0.2)
856
857 for _ in support.busy_retry(support.LONG_TIMEOUT):
858 # do some work
859 _ = sum(i * i for i in range(10**5))
860 if signal.getitimer(self.itimer) == (0.0, 0.0):
861 # sig_prof handler stopped this itimer
862 break
863
864 # profiling itimer should be (0.0, 0.0) now
865 self.assertEqual(signal.getitimer(self.itimer), (0.0, 0.0))
866 # and the handler should have been called
867 self.assertEqual(self.hndl_called, True)
868
869 def test_setitimer_tiny(self):
870 # bpo-30807: C setitimer() takes a microsecond-resolution interval.
871 # Check that float -> timeval conversion doesn't round
872 # the interval down to zero, which would disable the timer.
873 self.itimer = signal.ITIMER_REAL
874 signal.setitimer(self.itimer, 1e-6)
875 time.sleep(1)
876 self.assertEqual(self.hndl_called, True)
877
878
879 class PendingSignalsTests(unittest.TestCase):
880 """
881 Test pthread_sigmask(), pthread_kill(), sigpending() and sigwait()
882 functions.
883 """
884 @unittest.skipUnless(hasattr(signal, 'sigpending'),
885 'need signal.sigpending()')
886 def test_sigpending_empty(self):
887 self.assertEqual(signal.sigpending(), set())
888
889 @unittest.skipUnless(hasattr(signal, 'pthread_sigmask'),
890 'need signal.pthread_sigmask()')
891 @unittest.skipUnless(hasattr(signal, 'sigpending'),
892 'need signal.sigpending()')
893 def test_sigpending(self):
894 code = """if 1:
895 import os
896 import signal
897
898 def handler(signum, frame):
899 1/0
900
901 signum = signal.SIGUSR1
902 signal.signal(signum, handler)
903
904 signal.pthread_sigmask(signal.SIG_BLOCK, [signum])
905 os.kill(os.getpid(), signum)
906 pending = signal.sigpending()
907 for sig in pending:
908 assert isinstance(sig, signal.Signals), repr(pending)
909 if pending != {signum}:
910 raise Exception('%s != {%s}' % (pending, signum))
911 try:
912 signal.pthread_sigmask(signal.SIG_UNBLOCK, [signum])
913 except ZeroDivisionError:
914 pass
915 else:
916 raise Exception("ZeroDivisionError not raised")
917 """
918 assert_python_ok('-c', code)
919
920 @unittest.skipUnless(hasattr(signal, 'pthread_kill'),
921 'need signal.pthread_kill()')
922 @threading_helper.requires_working_threading()
923 def test_pthread_kill(self):
924 code = """if 1:
925 import signal
926 import threading
927 import sys
928
929 signum = signal.SIGUSR1
930
931 def handler(signum, frame):
932 1/0
933
934 signal.signal(signum, handler)
935
936 tid = threading.get_ident()
937 try:
938 signal.pthread_kill(tid, signum)
939 except ZeroDivisionError:
940 pass
941 else:
942 raise Exception("ZeroDivisionError not raised")
943 """
944 assert_python_ok('-c', code)
945
946 @unittest.skipUnless(hasattr(signal, 'pthread_sigmask'),
947 'need signal.pthread_sigmask()')
948 def wait_helper(self, blocked, test):
949 """
950 test: body of the "def test(signum):" function.
951 blocked: number of the blocked signal
952 """
953 code = '''if 1:
954 import signal
955 import sys
956 from signal import Signals
957
958 def handler(signum, frame):
959 1/0
960
961 %s
962
963 blocked = %s
964 signum = signal.SIGALRM
965
966 # child: block and wait the signal
967 try:
968 signal.signal(signum, handler)
969 signal.pthread_sigmask(signal.SIG_BLOCK, [blocked])
970
971 # Do the tests
972 test(signum)
973
974 # The handler must not be called on unblock
975 try:
976 signal.pthread_sigmask(signal.SIG_UNBLOCK, [blocked])
977 except ZeroDivisionError:
978 print("the signal handler has been called",
979 file=sys.stderr)
980 sys.exit(1)
981 except BaseException as err:
982 print("error: {}".format(err), file=sys.stderr)
983 sys.stderr.flush()
984 sys.exit(1)
985 ''' % (test.strip(), blocked)
986
987 # sig*wait* must be called with the signal blocked: since the current
988 # process might have several threads running, use a subprocess to have
989 # a single thread.
990 assert_python_ok('-c', code)
991
992 @unittest.skipUnless(hasattr(signal, 'sigwait'),
993 'need signal.sigwait()')
994 def test_sigwait(self):
995 self.wait_helper(signal.SIGALRM, '''
996 def test(signum):
997 signal.alarm(1)
998 received = signal.sigwait([signum])
999 assert isinstance(received, signal.Signals), received
1000 if received != signum:
1001 raise Exception('received %s, not %s' % (received, signum))
1002 ''')
1003
1004 @unittest.skipUnless(hasattr(signal, 'sigwaitinfo'),
1005 'need signal.sigwaitinfo()')
1006 def test_sigwaitinfo(self):
1007 self.wait_helper(signal.SIGALRM, '''
1008 def test(signum):
1009 signal.alarm(1)
1010 info = signal.sigwaitinfo([signum])
1011 if info.si_signo != signum:
1012 raise Exception("info.si_signo != %s" % signum)
1013 ''')
1014
1015 @unittest.skipUnless(hasattr(signal, 'sigtimedwait'),
1016 'need signal.sigtimedwait()')
1017 def test_sigtimedwait(self):
1018 self.wait_helper(signal.SIGALRM, '''
1019 def test(signum):
1020 signal.alarm(1)
1021 info = signal.sigtimedwait([signum], 10.1000)
1022 if info.si_signo != signum:
1023 raise Exception('info.si_signo != %s' % signum)
1024 ''')
1025
1026 @unittest.skipUnless(hasattr(signal, 'sigtimedwait'),
1027 'need signal.sigtimedwait()')
1028 def test_sigtimedwait_poll(self):
1029 # check that polling with sigtimedwait works
1030 self.wait_helper(signal.SIGALRM, '''
1031 def test(signum):
1032 import os
1033 os.kill(os.getpid(), signum)
1034 info = signal.sigtimedwait([signum], 0)
1035 if info.si_signo != signum:
1036 raise Exception('info.si_signo != %s' % signum)
1037 ''')
1038
1039 @unittest.skipUnless(hasattr(signal, 'sigtimedwait'),
1040 'need signal.sigtimedwait()')
1041 def test_sigtimedwait_timeout(self):
1042 self.wait_helper(signal.SIGALRM, '''
1043 def test(signum):
1044 received = signal.sigtimedwait([signum], 1.0)
1045 if received is not None:
1046 raise Exception("received=%r" % (received,))
1047 ''')
1048
1049 @unittest.skipUnless(hasattr(signal, 'sigtimedwait'),
1050 'need signal.sigtimedwait()')
1051 def test_sigtimedwait_negative_timeout(self):
1052 signum = signal.SIGALRM
1053 self.assertRaises(ValueError, signal.sigtimedwait, [signum], -1.0)
1054
1055 @unittest.skipUnless(hasattr(signal, 'sigwait'),
1056 'need signal.sigwait()')
1057 @unittest.skipUnless(hasattr(signal, 'pthread_sigmask'),
1058 'need signal.pthread_sigmask()')
1059 @threading_helper.requires_working_threading()
1060 def test_sigwait_thread(self):
1061 # Check that calling sigwait() from a thread doesn't suspend the whole
1062 # process. A new interpreter is spawned to avoid problems when mixing
1063 # threads and fork(): only async-safe functions are allowed between
1064 # fork() and exec().
1065 assert_python_ok("-c", """if True:
1066 import os, threading, sys, time, signal
1067
1068 # the default handler terminates the process
1069 signum = signal.SIGUSR1
1070
1071 def kill_later():
1072 # wait until the main thread is waiting in sigwait()
1073 time.sleep(1)
1074 os.kill(os.getpid(), signum)
1075
1076 # the signal must be blocked by all the threads
1077 signal.pthread_sigmask(signal.SIG_BLOCK, [signum])
1078 killer = threading.Thread(target=kill_later)
1079 killer.start()
1080 received = signal.sigwait([signum])
1081 if received != signum:
1082 print("sigwait() received %s, not %s" % (received, signum),
1083 file=sys.stderr)
1084 sys.exit(1)
1085 killer.join()
1086 # unblock the signal, which should have been cleared by sigwait()
1087 signal.pthread_sigmask(signal.SIG_UNBLOCK, [signum])
1088 """)
1089
1090 @unittest.skipUnless(hasattr(signal, 'pthread_sigmask'),
1091 'need signal.pthread_sigmask()')
1092 def test_pthread_sigmask_arguments(self):
1093 self.assertRaises(TypeError, signal.pthread_sigmask)
1094 self.assertRaises(TypeError, signal.pthread_sigmask, 1)
1095 self.assertRaises(TypeError, signal.pthread_sigmask, 1, 2, 3)
1096 self.assertRaises(OSError, signal.pthread_sigmask, 1700, [])
1097 with self.assertRaises(ValueError):
1098 signal.pthread_sigmask(signal.SIG_BLOCK, [signal.NSIG])
1099 with self.assertRaises(ValueError):
1100 signal.pthread_sigmask(signal.SIG_BLOCK, [0])
1101 with self.assertRaises(ValueError):
1102 signal.pthread_sigmask(signal.SIG_BLOCK, [1<<1000])
1103
1104 @unittest.skipUnless(hasattr(signal, 'pthread_sigmask'),
1105 'need signal.pthread_sigmask()')
1106 def test_pthread_sigmask_valid_signals(self):
1107 s = signal.pthread_sigmask(signal.SIG_BLOCK, signal.valid_signals())
1108 self.addCleanup(signal.pthread_sigmask, signal.SIG_SETMASK, s)
1109 # Get current blocked set
1110 s = signal.pthread_sigmask(signal.SIG_UNBLOCK, signal.valid_signals())
1111 self.assertLessEqual(s, signal.valid_signals())
1112
1113 @unittest.skipUnless(hasattr(signal, 'pthread_sigmask'),
1114 'need signal.pthread_sigmask()')
1115 @threading_helper.requires_working_threading()
1116 def test_pthread_sigmask(self):
1117 code = """if 1:
1118 import signal
1119 import os; import threading
1120
1121 def handler(signum, frame):
1122 1/0
1123
1124 def kill(signum):
1125 os.kill(os.getpid(), signum)
1126
1127 def check_mask(mask):
1128 for sig in mask:
1129 assert isinstance(sig, signal.Signals), repr(sig)
1130
1131 def read_sigmask():
1132 sigmask = signal.pthread_sigmask(signal.SIG_BLOCK, [])
1133 check_mask(sigmask)
1134 return sigmask
1135
1136 signum = signal.SIGUSR1
1137
1138 # Install our signal handler
1139 old_handler = signal.signal(signum, handler)
1140
1141 # Unblock SIGUSR1 (and copy the old mask) to test our signal handler
1142 old_mask = signal.pthread_sigmask(signal.SIG_UNBLOCK, [signum])
1143 check_mask(old_mask)
1144 try:
1145 kill(signum)
1146 except ZeroDivisionError:
1147 pass
1148 else:
1149 raise Exception("ZeroDivisionError not raised")
1150
1151 # Block and then raise SIGUSR1. The signal is blocked: the signal
1152 # handler is not called, and the signal is now pending
1153 mask = signal.pthread_sigmask(signal.SIG_BLOCK, [signum])
1154 check_mask(mask)
1155 kill(signum)
1156
1157 # Check the new mask
1158 blocked = read_sigmask()
1159 check_mask(blocked)
1160 if signum not in blocked:
1161 raise Exception("%s not in %s" % (signum, blocked))
1162 if old_mask ^ blocked != {signum}:
1163 raise Exception("%s ^ %s != {%s}" % (old_mask, blocked, signum))
1164
1165 # Unblock SIGUSR1
1166 try:
1167 # unblock the pending signal calls immediately the signal handler
1168 signal.pthread_sigmask(signal.SIG_UNBLOCK, [signum])
1169 except ZeroDivisionError:
1170 pass
1171 else:
1172 raise Exception("ZeroDivisionError not raised")
1173 try:
1174 kill(signum)
1175 except ZeroDivisionError:
1176 pass
1177 else:
1178 raise Exception("ZeroDivisionError not raised")
1179
1180 # Check the new mask
1181 unblocked = read_sigmask()
1182 if signum in unblocked:
1183 raise Exception("%s in %s" % (signum, unblocked))
1184 if blocked ^ unblocked != {signum}:
1185 raise Exception("%s ^ %s != {%s}" % (blocked, unblocked, signum))
1186 if old_mask != unblocked:
1187 raise Exception("%s != %s" % (old_mask, unblocked))
1188 """
1189 assert_python_ok('-c', code)
1190
1191 @unittest.skipUnless(hasattr(signal, 'pthread_kill'),
1192 'need signal.pthread_kill()')
1193 @threading_helper.requires_working_threading()
1194 def test_pthread_kill_main_thread(self):
1195 # Test that a signal can be sent to the main thread with pthread_kill()
1196 # before any other thread has been created (see issue #12392).
1197 code = """if True:
1198 import threading
1199 import signal
1200 import sys
1201
1202 def handler(signum, frame):
1203 sys.exit(3)
1204
1205 signal.signal(signal.SIGUSR1, handler)
1206 signal.pthread_kill(threading.get_ident(), signal.SIGUSR1)
1207 sys.exit(2)
1208 """
1209
1210 with spawn_python('-c', code) as process:
1211 stdout, stderr = process.communicate()
1212 exitcode = process.wait()
1213 if exitcode != 3:
1214 raise Exception("Child error (exit code %s): %s" %
1215 (exitcode, stdout))
1216
1217
1218 class StressTest(unittest.TestCase):
1219 """
1220 Stress signal delivery, especially when a signal arrives in
1221 the middle of recomputing the signal state or executing
1222 previously tripped signal handlers.
1223 """
1224
1225 def setsig(self, signum, handler):
1226 old_handler = signal.signal(signum, handler)
1227 self.addCleanup(signal.signal, signum, old_handler)
1228
1229 def measure_itimer_resolution(self):
1230 N = 20
1231 times = []
1232
1233 def handler(signum=None, frame=None):
1234 if len(times) < N:
1235 times.append(time.perf_counter())
1236 # 1 µs is the smallest possible timer interval,
1237 # we want to measure what the concrete duration
1238 # will be on this platform
1239 signal.setitimer(signal.ITIMER_REAL, 1e-6)
1240
1241 self.addCleanup(signal.setitimer, signal.ITIMER_REAL, 0)
1242 self.setsig(signal.SIGALRM, handler)
1243 handler()
1244 while len(times) < N:
1245 time.sleep(1e-3)
1246
1247 durations = [times[i+1] - times[i] for i in range(len(times) - 1)]
1248 med = statistics.median(durations)
1249 if support.verbose:
1250 print("detected median itimer() resolution: %.6f s." % (med,))
1251 return med
1252
1253 def decide_itimer_count(self):
1254 # Some systems have poor setitimer() resolution (for example
1255 # measured around 20 ms. on FreeBSD 9), so decide on a reasonable
1256 # number of sequential timers based on that.
1257 reso = self.measure_itimer_resolution()
1258 if reso <= 1e-4:
1259 return 10000
1260 elif reso <= 1e-2:
1261 return 100
1262 else:
1263 self.skipTest("detected itimer resolution (%.3f s.) too high "
1264 "(> 10 ms.) on this platform (or system too busy)"
1265 % (reso,))
1266
1267 @unittest.skipUnless(hasattr(signal, "setitimer"),
1268 "test needs setitimer()")
1269 def test_stress_delivery_dependent(self):
1270 """
1271 This test uses dependent signal handlers.
1272 """
1273 N = self.decide_itimer_count()
1274 sigs = []
1275
1276 def first_handler(signum, frame):
1277 # 1e-6 is the minimum non-zero value for `setitimer()`.
1278 # Choose a random delay so as to improve chances of
1279 # triggering a race condition. Ideally the signal is received
1280 # when inside critical signal-handling routines such as
1281 # Py_MakePendingCalls().
1282 signal.setitimer(signal.ITIMER_REAL, 1e-6 + random.random() * 1e-5)
1283
1284 def second_handler(signum=None, frame=None):
1285 sigs.append(signum)
1286
1287 # Here on Linux, SIGPROF > SIGALRM > SIGUSR1. By using both
1288 # ascending and descending sequences (SIGUSR1 then SIGALRM,
1289 # SIGPROF then SIGALRM), we maximize chances of hitting a bug.
1290 self.setsig(signal.SIGPROF, first_handler)
1291 self.setsig(signal.SIGUSR1, first_handler)
1292 self.setsig(signal.SIGALRM, second_handler) # for ITIMER_REAL
1293
1294 expected_sigs = 0
1295 deadline = time.monotonic() + support.SHORT_TIMEOUT
1296
1297 while expected_sigs < N:
1298 os.kill(os.getpid(), signal.SIGPROF)
1299 expected_sigs += 1
1300 # Wait for handlers to run to avoid signal coalescing
1301 while len(sigs) < expected_sigs and time.monotonic() < deadline:
1302 time.sleep(1e-5)
1303
1304 os.kill(os.getpid(), signal.SIGUSR1)
1305 expected_sigs += 1
1306 while len(sigs) < expected_sigs and time.monotonic() < deadline:
1307 time.sleep(1e-5)
1308
1309 # All ITIMER_REAL signals should have been delivered to the
1310 # Python handler
1311 self.assertEqual(len(sigs), N, "Some signals were lost")
1312
1313 @unittest.skipUnless(hasattr(signal, "setitimer"),
1314 "test needs setitimer()")
1315 def test_stress_delivery_simultaneous(self):
1316 """
1317 This test uses simultaneous signal handlers.
1318 """
1319 N = self.decide_itimer_count()
1320 sigs = []
1321
1322 def handler(signum, frame):
1323 sigs.append(signum)
1324
1325 # On Android, SIGUSR1 is unreliable when used in close proximity to
1326 # another signal – see Android/testbed/app/src/main/python/main.py.
1327 # So we use a different signal.
1328 self.setsig(signal.SIGUSR2, handler)
1329 self.setsig(signal.SIGALRM, handler) # for ITIMER_REAL
1330
1331 expected_sigs = 0
1332 while expected_sigs < N:
1333 # Hopefully the SIGALRM will be received somewhere during
1334 # initial processing of SIGUSR2.
1335 signal.setitimer(signal.ITIMER_REAL, 1e-6 + random.random() * 1e-5)
1336 os.kill(os.getpid(), signal.SIGUSR2)
1337
1338 expected_sigs += 2
1339 # Wait for handlers to run to avoid signal coalescing
1340 for _ in support.sleeping_retry(support.SHORT_TIMEOUT):
1341 if len(sigs) >= expected_sigs:
1342 break
1343
1344 # All ITIMER_REAL signals should have been delivered to the
1345 # Python handler
1346 self.assertEqual(len(sigs), N, "Some signals were lost")
1347
1348 @support.requires_gil_enabled("gh-121065: test is flaky on free-threaded build")
1349 @unittest.skipIf(is_apple, "crashes due to system bug (FB13453490)")
1350 @unittest.skipUnless(hasattr(signal, "SIGUSR1"),
1351 "test needs SIGUSR1")
1352 @threading_helper.requires_working_threading()
1353 def test_stress_modifying_handlers(self):
1354 # bpo-43406: race condition between trip_signal() and signal.signal
1355 signum = signal.SIGUSR1
1356 num_sent_signals = 0
1357 num_received_signals = 0
1358 do_stop = False
1359
1360 def custom_handler(signum, frame):
1361 nonlocal num_received_signals
1362 num_received_signals += 1
1363
1364 def set_interrupts():
1365 nonlocal num_sent_signals
1366 while not do_stop:
1367 signal.raise_signal(signum)
1368 num_sent_signals += 1
1369
1370 def cycle_handlers():
1371 while num_sent_signals < 100 or num_received_signals < 1:
1372 for i in range(20000):
1373 # Cycle between a Python-defined and a non-Python handler
1374 for handler in [custom_handler, signal.SIG_IGN]:
1375 signal.signal(signum, handler)
1376
1377 old_handler = signal.signal(signum, custom_handler)
1378 self.addCleanup(signal.signal, signum, old_handler)
1379
1380 t = threading.Thread(target=set_interrupts)
1381 try:
1382 ignored = False
1383 with support.catch_unraisable_exception() as cm:
1384 t.start()
1385 cycle_handlers()
1386 do_stop = True
1387 t.join()
1388
1389 if cm.unraisable is not None:
1390 # An unraisable exception may be printed out when
1391 # a signal is ignored due to the aforementioned
1392 # race condition, check it.
1393 self.assertIsInstance(cm.unraisable.exc_value, OSError)
1394 self.assertIn(
1395 f"Signal {signum:d} ignored due to race condition",
1396 str(cm.unraisable.exc_value))
1397 ignored = True
1398
1399 # bpo-43406: Even if it is unlikely, it's technically possible that
1400 # all signals were ignored because of race conditions.
1401 if not ignored:
1402 # Sanity check that some signals were received, but not all
1403 self.assertGreater(num_received_signals, 0)
1404 self.assertLessEqual(num_received_signals, num_sent_signals)
1405 finally:
1406 do_stop = True
1407 t.join()
1408
1409
1410 class RaiseSignalTest(unittest.TestCase):
1411
1412 def test_sigint(self):
1413 with self.assertRaises(KeyboardInterrupt):
1414 signal.raise_signal(signal.SIGINT)
1415
1416 @unittest.skipIf(sys.platform != "win32", "Windows specific test")
1417 def test_invalid_argument(self):
1418 try:
1419 SIGHUP = 1 # not supported on win32
1420 signal.raise_signal(SIGHUP)
1421 self.fail("OSError (Invalid argument) expected")
1422 except OSError as e:
1423 if e.errno == errno.EINVAL:
1424 pass
1425 else:
1426 raise
1427
1428 def test_handler(self):
1429 is_ok = False
1430 def handler(a, b):
1431 nonlocal is_ok
1432 is_ok = True
1433 old_signal = signal.signal(signal.SIGINT, handler)
1434 self.addCleanup(signal.signal, signal.SIGINT, old_signal)
1435
1436 signal.raise_signal(signal.SIGINT)
1437 self.assertTrue(is_ok)
1438
1439 def test__thread_interrupt_main(self):
1440 # See https://github.com/python/cpython/issues/102397
1441 code = """if 1:
1442 import _thread
1443 class Foo():
1444 def __del__(self):
1445 _thread.interrupt_main()
1446
1447 x = Foo()
1448 """
1449
1450 rc, out, err = assert_python_ok('-c', code)
1451 self.assertIn(b'OSError: Signal 2 ignored due to race condition', err)
1452
1453
1454
1455 class PidfdSignalTest(unittest.TestCase):
1456
1457 @unittest.skipUnless(
1458 hasattr(signal, "pidfd_send_signal"),
1459 "pidfd support not built in",
1460 )
1461 def test_pidfd_send_signal(self):
1462 with self.assertRaises(OSError) as cm:
1463 signal.pidfd_send_signal(0, signal.SIGINT)
1464 if cm.exception.errno == errno.ENOSYS:
1465 self.skipTest("kernel does not support pidfds")
1466 elif cm.exception.errno == errno.EPERM:
1467 self.skipTest("Not enough privileges to use pidfs")
1468 self.assertEqual(cm.exception.errno, errno.EBADF)
1469 my_pidfd = os.open(f'/proc/{os.getpid()}', os.O_DIRECTORY)
1470 self.addCleanup(os.close, my_pidfd)
1471 with self.assertRaisesRegex(TypeError, "^siginfo must be None$"):
1472 signal.pidfd_send_signal(my_pidfd, signal.SIGINT, object(), 0)
1473 with self.assertRaises(KeyboardInterrupt):
1474 signal.pidfd_send_signal(my_pidfd, signal.SIGINT)
1475
1476 def tearDownModule():
1477 support.reap_children()
1478
1479 if __name__ == "__main__":
1480 unittest.main()