|
4 | 4 | import sys |
5 | 5 | import re |
6 | 6 | import zmq # Added for ZeroMQ |
| 7 | +import atexit |
| 8 | +import signal |
7 | 9 |
|
8 | 10 | # if windows, create script to kill this process |
9 | 11 | # 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): |
92 | 94 | print(f"An unexpected error occurred during ZMQ port initialization for {port_name}: {e}") |
93 | 95 |
|
94 | 96 | 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(): |
96 | 103 | try: |
97 | 104 | port.socket.close() |
98 | 105 | port.context.term() |
| 106 | + print(f"Closed ZMQ port: {port_name}") |
99 | 107 | 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 | + |
101 | 122 | # --- ZeroMQ Integration End --- |
102 | 123 |
|
103 | 124 | # =================================================================== |
|
0 commit comments