我有一個Python應用程序,它打開一個簡單的TCP套接字與另一個主機上的另一個Python應用程序通信。有時程序會出錯,或者我會直接殺死它,並且在任何一種情況下,套接字可能會在未知的時間保持打開狀態。如何關閉被死程序打開的插槽?
下一次我去運行程序我得到這個錯誤:
socket.error: [Errno 98] Address already in use
現在的程序總是使用相同的端口,所以它看起來好像它仍然是開放的。我查了一下,很確定這個程序沒有在後臺運行,但我的地址仍在使用中。那麼,我該如何手動(或以其他方式)關閉套接字/地址,以便我的程序可以立即重新使用它?
更新
基於邁克的回答我檢查了socket(7)
頁,看着SO_REUSEADDR:
SO_REUSEADDR Indicates that the rules used in validating addresses supplied in a bind(2) call should allow reuse of local addresses. For AF_INET sockets this means that a socket may bind, except when there is an active listening socket bound to the address. When the listen‐ ing socket is bound to INADDR_ANY with a specific port then it is not possible to bind to this port for any local address. Argument is an integer boolean flag.
任何反對將此轉移到SO?它最終是一個完全的編程問題,所以它可能更有意義 – 2011-05-03 16:03:45
一點都不,我只在這裏發佈這個,因爲我正在考慮關閉套接字的Linux命令,我同意它的編程材料。也許標題可能會改變,以反映它是一個Python程序。 – 2011-05-03 18:57:26
@Mr。 Shickadance遷移了,如果你覺得有必要,你必須重新標題。 – xenoterracide 2011-05-03 20:18:23