首页 > 解决方案 > 如何实现信号处理?

问题描述

我正在尝试开发一个 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'

标签: pythonwindowssignalspython-sockets

解决方案


请注意,这signal.SIGALRM仅在 Unix 上可用。

由于您使用的是 Windows 机器,请注意signal 文档中的说明:

在 Windows 上,signal()只能用SIGABRT, SIGFPE, SIGILL, SIGINT, SIGSEGV, SIGTERM, 或调用SIGBREAKValueError在任何其他情况下都会引发A。请注意,并非所有系统都定义相同的信号名称集;AttributeError如果信号名称未定义为SIG*模块级常量,则会引发an 。


推荐阅读