程序退出了,listen的埠沒有釋放
阿新 • • 發佈:2022-11-30
場景:程序A建立程序B,程序A listen埠P。程序A退出,程序B仍在,此時程序A listen的埠P沒有被釋放。
原因:程序建立時,預設是共享資源的。這種情況下,程序A的的埠不會回收,因為檔案描述符的引用計數仍在。
解決方案:建立socket時,設定屬性,埠資源不可被繼承。
zmq程式碼參考
zmq::fd_t zmq::open_socket (int domain_, int type_, int protocol_) { // Setting this option result in sane behaviour when exec() functions // are used. Old sockets are closed and don't block TCP ports etc. #if defined ZMQ_HAVE_SOCK_CLOEXEC type_ |= SOCK_CLOEXEC; #endif fd_t s = socket (domain_, type_, protocol_); #ifdef ZMQ_HAVE_WINDOWS if (s == INVALID_SOCKET) return INVALID_SOCKET; #else if (s == -1) return -1; #endif // If there's no SOCK_CLOEXEC, let's try the second best option. Note that // race condition can cause socket not to be closed (if fork happens // between socket creation and this point). #if !defined ZMQ_HAVE_SOCK_CLOEXEC && defined FD_CLOEXEC int rc = fcntl (s, F_SETFD, FD_CLOEXEC); errno_assert (rc != -1); #endif // On Windows, preventing sockets to be inherited by child processes. #if defined ZMQ_HAVE_WINDOWS && defined HANDLE_FLAG_INHERIT BOOL brc = SetHandleInformation ((HANDLE) s, HANDLE_FLAG_INHERIT, 0); win_assert (brc); #endif return s; }