Skip to content

Commit c51c041

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 3b6756b commit c51c041

1 file changed

Lines changed: 23 additions & 2 deletions

File tree

concore.py

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
import sys
55
import re
66
import zmq # Added for ZeroMQ
7+
import atexit
8+
import signal
79

810
# if windows, create script to kill this process
911
# because batch files don't provide easy way to know pid of last command
@@ -92,12 +94,31 @@ def init_zmq_port(port_name, port_type, address, socket_type_str):
9294
print(f"An unexpected error occurred during ZMQ port initialization for {port_name}: {e}")
9395

9496
def terminate_zmq():
95-
for port in zmq_ports.values():
97+
"""Clean up all ZMQ sockets and contexts before exit."""
98+
if not zmq_ports:
99+
return # No ports to clean up
100+
101+
print("\nCleaning up ZMQ resources...")
102+
for port_name, port in zmq_ports.items():
96103
try:
97104
port.socket.close()
98105
port.context.term()
106+
print(f"Closed ZMQ port: {port_name}")
99107
except Exception as e:
100-
print(f"Error while terminating ZMQ port {port.address}: {e}")
108+
print(f"Error while terminating ZMQ port {port_name} ({port.address}): {e}")
109+
zmq_ports.clear()
110+
111+
def signal_handler(sig, frame):
112+
"""Handle interrupt signals gracefully."""
113+
print(f"\nReceived signal {sig}, shutting down gracefully...")
114+
terminate_zmq()
115+
sys.exit(0)
116+
117+
# Register cleanup handlers
118+
atexit.register(terminate_zmq)
119+
signal.signal(signal.SIGINT, signal_handler) # Handle Ctrl+C
120+
signal.signal(signal.SIGTERM, signal_handler) # Handle termination
121+
101122
# --- ZeroMQ Integration End ---
102123

103124
# ===================================================================

0 commit comments

Comments
 (0)