【问题标题】:How can a process find the pids of processes it communicates with over a pipe?进程如何找到通过管道与之通信的进程的 pid?
【发布时间】:2012-09-20 06:17:03
【问题描述】:

假设我有以下管道:

$ generator_process | filter_process | storage_process

filter_process 是否可以找出generator_processstorage_process 的pid?如果是这样,怎么做?如果不是,为什么?

更一般地说,进程如何找到通过管道与之通信的进程的 pid?

我正在寻找一种可移植的 (POSIX) 方式来执行此操作,但如果它需要一些特定于平台的技巧,那么我正在寻找一种 Linux 解决方案。我想 C 中的答案会给出最详细的信息,但如果它涉及 shell,我正在寻找 bash 解决方案。

请假设我可以更改filter_process,但generator_processstorage_process 是我不可能或不想更改的程序(它们可能是我不想摆弄的标准Unix 工具)。此外,将它们包装在将它们的 pid 写入磁盘的脚本中并不是我想要的解决方案。

【问题讨论】:

标签: unix process ipc pipe pid


【解决方案1】:

请注意,管道的一端可能同时在多个进程中打开(通过fork()sendmsg 文件描述符传输),因此您可能不会只得到一个答案。

在 Linux 中,您可以检查 /proc/<pid>/fd 以查看它打开了哪些 fds(您需要是 root,或者与目标进程相同的 uid)。我刚刚运行grep a | grep b 并得到以下输出:

/proc/10442/fd:
total 0
dr-x------ 2 nneonneo nneonneo  0 Sep 20 02:19 .
dr-xr-xr-x 7 nneonneo nneonneo  0 Sep 20 02:19 ..
lrwx------ 1 nneonneo nneonneo 64 Sep 20 02:19 0 -> /dev/pts/5
l-wx------ 1 nneonneo nneonneo 64 Sep 20 02:19 1 -> pipe:[100815116]
lrwx------ 1 nneonneo nneonneo 64 Sep 20 02:19 2 -> /dev/pts/5

/proc/10443/fd:
total 0
dr-x------ 2 nneonneo nneonneo  0 Sep 20 02:19 .
dr-xr-xr-x 7 nneonneo nneonneo  0 Sep 20 02:19 ..
lr-x------ 1 nneonneo nneonneo 64 Sep 20 02:19 0 -> pipe:[100815116]
lrwx------ 1 nneonneo nneonneo 64 Sep 20 02:19 1 -> /dev/pts/5
lrwx------ 1 nneonneo nneonneo 64 Sep 20 02:19 2 -> /dev/pts/5

因此,通过在您自己进程的 fd 上使用 readlink,然后在您拥有的其他进程 fd 上使用 readlink,您可以确定谁在管道的另一端。

找出(从 Bash 脚本中)哪些 pid 和 fd 连接到特定管道的疯狂黑客方式:

get_fd_target() {
    pid=$1
    fd=$2
    readlink /proc/$pid/fd/$fd
}

find_fd_target() {
    target=$1
    for i in /proc/*/fd/*; do
        if [ "`readlink $i`" == "$target" ]; then
            echo $i
        fi
    done
}

那么,如果你想找出系统上的哪些 fds 连接到你的脚本的标准输入:

find_fd_target `get_fd_target $$ 0`

【讨论】:

  • 这几乎是解决方案,至少对于 Linux 而言。通过适当的扩展,我可以区分读取器和写入器进程。谢谢!
猜你喜欢
  • 2013-04-01
  • 2021-12-16
  • 2017-09-10
  • 2011-12-22
  • 1970-01-01
  • 1970-01-01
  • 2022-12-10
  • 2010-12-11
  • 1970-01-01
相关资源
最近更新 更多