I have tried set signal handler with sigaction and ctypes. (I know it is able to do with signal module in python, but I want to try it for learn.)
When I sent SIGTERM to this process, but it does not call handler that I set, only print "Terminated". Why it does not invoke the handler?
I using Ubuntu 19.10 and Python 3.7.5 x64.
import ctypes
from ctypes import *
from ctypes.util import *
from os import getpid
class sigset_t(Structure):
__fields__ = [
("__val", c_ulong*16)
]
class sigval_t(Union):
__fields__ = [
("sival_int", c_int),
("sival_ptr", c_void_p)
]
class siginfo_t(Structure):
__fields__ = [
("si_signo", c_int),
("si_errno", c_int),
("si_code", c_int),
("si_trapno", c_int),
("si_pid", c_uint),
("si_status", c_int),
("si_utime", c_long),
("si_stime", c_long),
("si_value", sigval_t),
("si_int", c_int),
("si_ptr", c_void_p),
("si_overrun", c_int),
("si_timerid", c_int),
("si_addr", c_void_p),
("si_band", c_long),
("si_fd", c_int),
("si_addr_lsb", c_short),
("si_call_addr", c_void_p),
("si_syscall", c_int),
("si_arch", c_uint)
]
sa_handler_functype = CFUNCTYPE(None, c_int)
sigaction_functype = CFUNCTYPE(None, c_int, siginfo_t, c_void_p)
class SIGACTION(Structure):
__fields__ = [
("sa_handler", sa_handler_functype),
("sa_sigaction", sigaction_functype),
("sa_mask", sigset_t),
("sa_flags", c_int),
]
def p(sig): # signal handler function
libc.puts("bye")
libc_path = find_library("c")
libc = CDLL(libc_path)
libc.sigaction.restype = c_int
libc.sigaction.argtypes = [c_int, POINTER(SIGACTION), POINTER(SIGACTION)]
act = SIGACTION(sa_handler=sa_handler_functype(p))
print(act)
res = libc.sigaction(15, act, None)
print(res)
print("pid:", getpid()) # show pid
while True: # wait until receive sigterm signal
pass