0

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'
martineau
  • 119,623
  • 25
  • 170
  • 301
  • The code seems to run fine. Not sure of your structure, but it may be that you have a file named signal.py which it is importing, although that seems weird because signal.signal() was found. Another possibility is that the module got messed up somehow, which you may need to reinstall. Hopefully something there helps. – Misha Melnyk Apr 14 '20 at 10:23
  • 1
    Related: [Setting timeout limit on Windows with Python 3.7](https://stackoverflow.com/q/56356125/132382), [Is it possible to specify the max amount of time to wait for code to run with Python?](https://stackoverflow.com/q/56305195/132382), and [python: windows equivalent of SIGALRM](https://stackoverflow.com/q/8420422/132382). – pilcrow Apr 14 '20 at 12:45

1 Answers1

1

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
Daniel Ocando
  • 3,554
  • 2
  • 11
  • 19