Home > other >  Redirect application output to unix socket
Redirect application output to unix socket

Time:12-04

I have a socket server which creates unix socket and then reads data from this unix socket. Then I have another long-process application and I want to redirect stdout of this process to my unix socket. I tried this command to test

ping 127.0.0.1 > /tmp/unixsockettest.sock

But I get -bash: /tmp/unixsockettest.sock: No such device or address. Is it possible to redirect application output to unix socket?

CodePudding user response:

You can't redirect out to a Unix socket using shell i/o redirection, but you can use a tool like socat (which is probably packaged for your distribution) to accomplish the task:

ping 127.0.0.1 | socat - unix-connect:/tmp/unixsockettest.sock

CodePudding user response:

Shell redirection tries to open() its target file and then dup2() the resulting filedescriptor into the right place. Unfortunately, UNIX sockets cannot be opened. The way to get a writable filedescriptor from a UNIX socket (streaming or datagram) is to connect() to it (after you've stuffed the path into a struct sockaddr_un). Shells will not do this for you, unfortunately, but you can pipe into tools like socat or netcat, which will do the connection and then shovel their piped input into the connected socket descriptor.

E.g., with netcat, you'd do:

ping 127.0.0.1 | nc -U /tmp/unixsockettest.sock #add -u it the socket isn't streaming but datagram

(Having an UNIX derivative where opening a socket files would connect to them might not be a bad design choice for OS designers. An argument against it could be that it could cause opens to get blocked and that it might make them bother some other process (the binder) but both can happen already with named pipes anyway.)

  • Related