Search code examples
pythonwindowssignalspython-sockets

How to implement signal handling?


I am trying to develop a TCP server which listens to a port and implements signals to make sure it shuts down after a preconfigured duration. I am using a Windows 10 machine and after execution I am getting an error. Here is my code:

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

Here is the error:

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'

Solution

  • Notice that signal.SIGALRM is only available on Unix.

    Since you are using a Windows machine notice what is stated on the 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.