【问题标题】:How to implement signal handling?如何实现信号处理?
【发布时间】:2020-04-14 10:13:32
【问题描述】:

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

【问题讨论】:

标签: python windows signals python-sockets


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-09
    • 2012-02-14
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    相关资源
    最近更新 更多