Skip to content

Commit ff3206a

Browse files
committed
fix: add atexit and signal handlers for ZMQ cleanup
- Register terminate_zmq() with atexit to ensure cleanup on normal exit - Add signal handlers for SIGINT (Ctrl+C) and SIGTERM - Improve terminate_zmq() with better logging and error handling - Clear zmq_ports dict after cleanup to prevent double-cleanup
1 parent 0c1ed0d commit ff3206a

1 file changed

Lines changed: 23 additions & 1 deletion

File tree

concore.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66
import re
77
import zmq
88
import numpy as np
9+
import atexit
10+
import signal
11+
912
logging.basicConfig(
1013
level=logging.INFO,
1114
format='%(levelname)s - %(message)s'
@@ -98,12 +101,31 @@ def init_zmq_port(port_name, port_type, address, socket_type_str):
98101
logging.error(f"An unexpected error occurred during ZMQ port initialization for {port_name}: {e}")
99102

100103
def terminate_zmq():
101-
for port in zmq_ports.values():
104+
"""Clean up all ZMQ sockets and contexts before exit."""
105+
if not zmq_ports:
106+
return # No ports to clean up
107+
108+
print("\nCleaning up ZMQ resources...")
109+
for port_name, port in zmq_ports.items():
102110
try:
103111
port.socket.close()
104112
port.context.term()
113+
print(f"Closed ZMQ port: {port_name}")
105114
except Exception as e:
106115
logging.error(f"Error while terminating ZMQ port {port.address}: {e}")
116+
zmq_ports.clear()
117+
118+
def signal_handler(sig, frame):
119+
"""Handle interrupt signals gracefully."""
120+
print(f"\nReceived signal {sig}, shutting down gracefully...")
121+
terminate_zmq()
122+
sys.exit(0)
123+
124+
# Register cleanup handlers
125+
atexit.register(terminate_zmq)
126+
signal.signal(signal.SIGINT, signal_handler) # Handle Ctrl+C
127+
signal.signal(signal.SIGTERM, signal_handler) # Handle termination
128+
107129
# --- ZeroMQ Integration End ---
108130

109131

0 commit comments

Comments
 (0)