如何获得unix domain socket的对端PID

1. 什么是unix domain socket

http://en.wikipedia.org/wiki/Unix_domain_socket

2. 有两种方法,第一种是通过猜测,第二种是debug linux内核

第一种方法的示例:

[test@localhost ipc]$  /usr/sbin/lsof -p 31854
COMMAND   PID     USER   FD   TYPE             DEVICE SIZE/OFF      NODE NAME
server  31854 test  cwd    DIR               0,26     4096  15746636 /home/test/workspace_ipc/ipc
server  31854 test  rtd    DIR                8,2     4096         2 /
server  31854 test  txt    REG               0,26     8702  15746641 /home/test/workspace_ipc/ipc/server
server  31854 test  mem    REG                8,2   144776  52035586 /lib64/ld-2.5.so
server  31854 test  mem    REG                8,2  1722328  52035588 /lib64/libc-2.5.so
server  31854 test    0u   CHR              136,2      0t0         4 /dev/pts/2
server  31854 test    1u   CHR              136,2      0t0         4 /dev/pts/2
server  31854 test    2u   CHR              136,2      0t0         4 /dev/pts/2
server  31854 test    3u  unix 0xffff8101c8d39180      0t0 650000043 ./socket
[test@localhost ipc]$  /usr/sbin/lsof -p 32028
COMMAND   PID     USER   FD   TYPE             DEVICE SIZE/OFF      NODE NAME
client  32028 test  cwd    DIR               0,26     4096  15746636 /home/test/workspace_ipc/ipc
client  32028 test  rtd    DIR                8,2     4096         2 /
client  32028 test  txt    REG               0,26     8199  15746715 /home/test/workspace_ipc/ipc/client
client  32028 test  mem    REG                8,2   144776  52035586 /lib64/ld-2.5.so
client  32028 test  mem    REG                8,2  1722328  52035588 /lib64/libc-2.5.so
client  32028 test    0u   CHR              136,2      0t0         4 /dev/pts/2
client  32028 test    1u   CHR              136,2      0t0         4 /dev/pts/2
client  32028 test    2u   CHR              136,2      0t0         4 /dev/pts/2
client  32028 test    3u  unix 0xffff810010eaa080      0t0 650002435 socket
[test@localhost ipc]$ netstat -na | grep 65000
unix  2      [ ACC ]     STREAM     LISTENING     650000043 ./socket
unix  3      [ ]         STREAM     CONNECTED     650002215 ./socket
unix  3      [ ]         STREAM     CONNECTED     650002435

上例中是通过65000来grep的,这就是猜测。

第二种方法:

http://stackoverflow.com/questions/11897662/identify-other-end-of-a-unix-
domain-socket-connection

http://unix.stackexchange.com/questions/16300/whos-got-the-other-end-of-
this-unix-socketpair

不能直接获得对端的信息的原因是,因linux内核对user space是不可见的。

The number shown in /proc/$pid/fd/$fd is the socket’s inode number in the
virtual socket filesystem. When you create a pipe or socket pair, each end
successively receives an inode number. The numbers are attributed
sequentially, so there is a high probability that the numbers differ by 1, but
this is not guaranteed (either because the first socket was _N_ and _N_ +1 was
already in use due to wrapping, or because some other thread was scheduled
between the two inode allocations and that thread created some inodes too).