进程之间传递文件描述符
日期:2014-04-21 17:52:14
最后更新日期:2014-04-26 11:34:54
参考1的结果如下:
[code lang="cpp"]
[root@localhost proc]# ps -elf | grep bout
0 S root 8238 7938 0 80 0 - 2969 wait 17:44 pts/2 00:00:00 ./bout
1 S root 8239 8238 0 80 0 - 2969 pause 17:44 pts/2 00:00:00 ./bout
0 S root 8243 7938 0 80 0 - 25813 pipe_w 17:44 pts/2 00:00:00 grep bout
[root@localhost proc]# ls -lh 8238/fd
总用量 0
lrwx------. 1 root root 64 4月 21 17:44 0 -> /dev/pts/2
lrwx------. 1 root root 64 4月 21 17:44 1 -> /dev/pts/2
lrwx------. 1 root root 64 4月 21 17:44 2 -> /dev/pts/2
lrwx------. 1 root root 64 4月 21 17:44 3 -> socket:[28795]
lrwx------. 1 root root 64 4月 21 17:44 4 -> socket:[28796]
lrwx------. 1 root root 64 4月 21 17:44 5 -> /tmp/bar.txt
[root@localhost proc]# ls -lh 8239/fd
总用量 0
lrwx------. 1 root root 64 4月 21 17:44 0 -> /dev/pts/2
lrwx------. 1 root root 64 4月 21 17:44 1 -> /dev/pts/2
lrwx------. 1 root root 64 4月 21 17:44 2 -> /dev/pts/2
lrwx------. 1 root root 64 4月 21 17:44 3 -> socket:[28795]
lrwx------. 1 root root 64 4月 21 17:44 4 -> socket:[28796]
lrwx------. 1 root root 64 4月 21 17:44 5 -> /tmp/foo.txt
lrwx------. 1 root root 64 4月 21 17:44 6 -> /tmp/bar.txt
[/code]
这两个进程是同一个可执行文件fork出来的。父进程8238打开/tmp/bar.txt,然后将该文件描述符传给子进程8239。注意子进程8239接收的描述符为6。
代码参考地址为http://blog.csdn.net/win_lin/article/details/7760951#comments,稍微修改代码让父子进程都不关闭fd,才会呈现上面的结果。