Unix-Sockets

如何創建公共 unix 域套接字?

  • September 21, 2018

考慮/var/run/acpid.socket。在任何時候,我都可以連接到它並從中斷開連接。將其與nc

$ nc -l -U ./myunixsocket.sock
Ncat: bind to ./myunixsocket.sock: Address already in use. QUITTING.

nc顯然只允許一次性使用的套接字。那麼問題是,我如何創建一個類似於 的套接字以/var/run/acpid.socket供多次使用和重用?

您可以-k選擇nc.

-k      Forces nc to stay listening for another connection after its cur-
         rent connection is completed.  It is an error to use this option
         without the -l option.  When used together with the -u option,
         the server socket is not connected and it can receive UDP data-
         grams from multiple hosts.

例子:

$ rm -f /tmp/socket    # unlink the socket if it already exists
$ nc -vklU /tmp/socket # the server
Connection from mack  received!
yes
Connection from mack  received!
yes
...

建議unlink()在使用後對套接字進行——但實際上,大多數程序會在呼叫它之前bind()檢查它是否存在並刪除它;如果文件系統中存在套接字路徑並且您嘗試訪問它,即使沒有程序以任何方式使用它bind(),您也會收到錯誤消息。EADDRINUSE

在 linux 上避免這種混亂的一種方法是使用“抽象” unix 套接字,但它們似乎不受netcat.

引用自:https://unix.stackexchange.com/questions/470459