$ any-process | receiver

Can receiver get the PID of the sending process?

  • No. There can be several pids connected to the pipe. For example, if I write { echo foo; sleep 3; cat /etc/passwd; sleep 5; echo bar; } | myCode, then all five processes on the left inherit the same write end of the pipe. They use the pipe in turn, only because the subshell runs them consecutively. Nov 11 '20 at 22:56
  • This could be a XY problem, what would "receiver" do wth this pid, for example send a signal once?
    – thanasisp
    Nov 12 '20 at 0:08
  • @thanasisp yes, you could monitor for certain output and then send a signal
    – laktak
    Nov 12 '20 at 8:49

Not directly. It could, but it would need to identify the pipe it is connected to, then search all other pid for one connected to that one.

Suppose receiver had pid 1730. It could look at /proc/self/fd/0 (or, more easily, /proc/self/fd/0) and see it shows as a symlink to pipe:[43270]. /proc/1730/fdinfo/0. Then it could discover that /proc/1729/fd/1 shows as a symlink to pipe:[43270], and on /proc/1729/fdinfo/1 see it has in flags 01. Thus, it found a process holding the other end of the pipe.

Please note:

  • this is a Linux-specific approach, non-portable and inefficient
  • multiple processes may be able to write into that pipe (also, the writing does not need to be at fd 1 at all)
  • it is prone to race conditions
  • if any-process is owned by a different user, receiver won'r be able to peek into their file descriptors

If what you want to do is to have two processes communicate in an authenticated way, you should use a unix socket. Through them it is possible via SO_PASSCRED option to use an ancillary message of type SCM_CREDENTIALS with the pid, uid and gid of the sender. The credentials which the sender specifies are checked by the kernel to ensure it cannot lie (unless it has appropriate capabilities, a root process / CAP_SYS_ADMIN would be able to specify a different process id than its own).


A simple way can be achived by redirecting the executing process to file descriptor 3, here is an example of sleep command that is piped to ps command :

( sleep 100 & echo $!>&3 ) 3>pid | ps -p "$(<pid)"

You can check the process of the command sleep :

ps -p $(<pid)
  • What is the purpose for not writing the pid directly to the file?
    – thanasisp
    Nov 12 '20 at 0:31
  • The purpose here is that the pid need to be used within the same command and piped to the next command, manipulating a file descriptor is more easy in this use case.
    – Reda Salih
    Nov 12 '20 at 1:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.