如何实现信号处理?

How to implement signal handling?

我正在尝试开发一个 TCP 服务器,它侦听端口并执行信号以确保它在预配置的持续时间后关闭。我正在使用 Windows 10 机器,执行后出现错误。这是我的代码:

import socket
import signal
import sys

# create the signal handler
def SigAlarmHandler(signal, frame):
    print("Received alarm... Shutting Down server...")
    sys.exit(0)


signal.signal(signal.SIGALRM, SigAlarmHandler)
signal.alarm(100)
print("Starting work... waiting for quiting time...")
while True:
    # define the target host and port
    host = '127.0.0.1'
    port = 444

    # define and create the server socket
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # bind the server to incoming client connection
    server.bind((host, port))

    # start the server listener
    server.listen(3)

    # establish connection with the client
    while True:
        client_socket, address = server.accept()
        print("connection received from %s" % str(address))
        message = 'thank you for connecting to the server' + "\r\n"
        client_socket.send(message.encode('ascii'))
        client_socket.close()
    pass

这里是错误:

Traceback (most recent call last):
  File "C:/Users/user/Desktop/pythons/tcpserver.py", line 19, in <module>
    signal.signal(signal.SIGALRM, SigAlarmHandler)
AttributeError: module 'signal' has no attribute 'SIGALRM'

请注意 signal.SIGALRM 仅适用于 Unix。

由于您使用的是 Windows 机器,请注意 signal documentation 上的说明:

On Windows, signal() can only be called with SIGABRT, SIGFPE, SIGILL, SIGINT, SIGSEGV, SIGTERM, or SIGBREAK. A ValueError will be raised in any other case. Note that not all systems define the same set of signal names; an AttributeError will be raised if a signal name is not defined as SIG* module level constant.