python - 如何实现信号处理?
问题描述
我正在尝试开发一个 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
文档中的说明:
在 Windows 上,
signal()
只能用SIGABRT
,SIGFPE
,SIGILL
,SIGINT
,SIGSEGV
,SIGTERM
, 或调用SIGBREAK
。ValueError
在任何其他情况下都会引发A。请注意,并非所有系统都定义相同的信号名称集;AttributeError
如果信号名称未定义为SIG*
模块级常量,则会引发an 。
推荐阅读
- firebase - 如何在flutter中过滤对firestore的查询?
- mysql - Debezium 引擎没有捕捉到我的 MySQL 数据库的变化
- c++ - 像素着色器中的 SamplerState 问题
- firebase - 是否可以将嵌套的 Kotlin 类转换为包含 Firestore 中子集合的集合?
- excel - 尝试使用 VBA Excel 创建表块
- google-cloud-platform - 将 VPN 隧道从项目 A 移动到项目 B - GCP
- pagerduty - 如何在团队之间移动服务?
- c - 如果我不在函数范围内,建议不会弹出
- javascript - 使用 .map() 在对象 React 中迭代数组
- go - 在golang中解释make的幕后?