Linux – No Such File or Device in /proc/[pid]/fd/[0, 1, 2] Despite File Existing

fifoipclinuxprocessunix-sockets

I'm trying to access a process' stdio streams from outside its parent process. I've found the /proc/[pid]/fd directory, but when I try

$ cat /proc/[pid]/fd/1

I get a No such file or device error. I know for certain that it exists, as Dolphin (file explorer) shows it.

I also happened to notice the file explorer lists it as a socket and trying to read from it as suggested here produces a similar error. This appeared odd to me as stdio streams are typically pipes, rather than sockets, so I'm not sure what's up here.

I'd like to point out also that the processes are started by the same user and attempting to access it with sudo didn't work either. I apologise if this question appears noobish, but I'd sincerely appreciate some guidance – perhaps there's a better way of accessing the stdio pipes?

Best Answer

tl;dr; As of 2020, you cannot do that (or anything similar) if /proc/<pid>/fd/<fd> is a socket.

The stdin, stdout, stderr of a process may be any kind of file, not necessarily pipes, regular files, etc. They can also be sockets.

On Linux, the /proc/<pid>/fd/<fd> are a special kind of symbolic links which allow you to open from the scratch the actual file a file descriptor refers to, and do it even if the file has been removed, or it didn't ever have any presence in any file system at all (e.g. a file created with memfd_create(2)).

But sockets are a notable exception, and they cannot be opened that way (nor is it obvious at all how that could be implemented: would an open() on /proc/<pid>/fd/<fd> create another connection to the server if that fd is a connected socket? what if the socket is explicitly bound to a local port?).

Recent versions of Linux kernels have introduced a new system call, pidfd_getfd(2), which allows you to "steal" a file descriptor from another process, in the same way you were able to pass it via Unix sockets, but without the collaboration of the victim process. But that hasn't yet made its way in most Linux distros.

Related Question