0

I have a python code which start a UDP communication on a port 5002. So what happens is when I first run the code, it works normally then I close the python script using ctlr z/ctrl c and then again run the code it shows me below error:

sock.bind(address)
OSError: [Errno 98] Address already in use

This may be because the python script is running and keeping the port busy. So it shows me the above error. To resolve this, I thought of running these two commands right before the code kills sock.close() to close the socket and sys.exit() to exit the python script properly. Thats why I need to know how can I run these commands right before the code is killed. I cannot use KeyboardInterrupt exception because in future this will be running as a service.

I found this answer but not able to implement it. For example, if I do:

import atexit
import time

def exit_handler():
    print("STOPPED")

while True:
    print("Running....")
    time.sleep(1)
    atexit.register(exit_handler)

This keeps on running but when I kill the code it doesn't print Stopped. How to implement it or is there any alternative way of handling my situation.

Thanks

9
  • 1
    stackoverflow.com/a/1112350/5270506 Commented Nov 24, 2017 at 10:44
  • stackoverflow.com/questions/4205317/… Commented Nov 24, 2017 at 10:46
  • @Farhan.K I do not want to kill the code with keyboard interrupt. There will be a service which will start or stop this code. So cannot use keyboard interrupts Commented Nov 24, 2017 at 10:47
  • Ah okay, I thought you meant keyboard interrupts because you mentioned ctlr z/ctrl c in the question Commented Nov 24, 2017 at 10:53
  • 1
    If you are getting "address already in use", it means that your script is still working (so you didn't kill it actually). If you actually killed it, it would free the resources and the port would be available. Commented Nov 24, 2017 at 10:55

1 Answer 1

1

The documentation of atexit module has an important note:

Note: The functions registered via this module are not called when the program is killed by a signal not handled by Python

That means that if you kill the script without special processing, the registered functions will not be called.

So you should instead register handlers for SIGTERM and SIGINT:

signal.signal(SIGTERM, (lambda signum, frame: exit_handler()))
signal.signal(SIGINT, (lambda signum, frame: exit_handler()))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.