Let’s say I have the following pipeline:
$ generator_process | filter_process | storage_process
Is it possible for filter_process to find out the pid of generator_process and storage_process? If so, how? If not, why?
More generally, how can a process find the pids of processes it communicates with over a pipe?
I’m looking for a portable (POSIX) way to do this, but if it requires some platform-specific trickery, a Linux solution is what I’m looking for. I guess an answer in C would give most detail but if it involves the shell, I’m looking for a bash solution.
Please assume that I can change filter_process but generator_process and storage_process are programs that I have no possibility or desire to alter (they could be standard Unix tools that I don’t want to fiddle with). Also, wrapping them in scripts that write their pids to disk is not the solution I’m after.
Note that one end of a pipe might be open in more than one process simultaneously (through
fork()orsendmsgfile-descriptor transmission), so you might not get just one answer.In Linux, you can examine
/proc/<pid>/fdto see whatfdsit has open (you need to beroot, or the same uid as the target process). I just rangrep a | grep band got the following output:So it follows that by using
readlinkon your own process’s fd, followed byreadlinkon other process fds you own, you can figure out who is on the other side of the pipe.Madly hackish way to find out (from within a Bash script) which pids and fds are connected to a particular pipe:
Then, if you want to find out what fds on the system are connected to your script’s stdin: