/dev/fd 文件描述符

来源:互联网 发布:python shell脚本 编辑:程序博客网 时间:2024/05/20 21:44

原文地址 https://discussions.apple.com/thread/2785618?tstart=0


提问:"WARNING: Can't open file /dev/fd/3: Permission denied" 


回答:It's nothing to worry about, it's actually a little bit of developer code to find the file descriptor of an application, not something a user needs to read or write so just forget about it.

More: +To understand what is going on, first note that "/dev/fd" is a "virtual" thing. It is a kind of a hack (developed for the use of shell scripts, I think) that gives a program a view of *its own* file descriptors.+

+This means that if I have two programs running (e.g., '/bin/bash' and '/usr/bin/du'), and each of those looks in "/dev/fd", they could see different things. Each will see one file for each file descriptor that it has open, and the name of the file will be the number of that open descriptor.+

+For example, by default, each program will have three open file descriptors, 0, 1, 2 (stdin, stdout, stderr). Different programs will have different ones open, so what you saw above is the result of that. The shell looked in "/dev/fd" and saw a number of files, one for each of its open files. The names were then passed to 'du' on the command line, as if the command were+
+du -ks /dev/fd/0 /dev/fd/1 /dev/fd/2 /dev/fd/3 ...+

+Then 'du' runs. Without looking at the code, I can only guess, but what has to be happening is that 'du' has closed FD 3, and when it tries to get information about '/dev/fd/3', the kernel gives it an error. The error is "EBADF" (see '/usr/include/sys/errno.h'), because access to "/dev/fd/3" is the same as accessing file descriptor 3 (for example, stat("/dev/fd/3",...) is the same as fstat(3,...))."+
http://lists.apple.com/archives/Darwinos-users/2004/Apr/msg00042.html


就我目前的水平,大概总结如下几点:

1. /dev/fd是一个虚拟的“东西”,它实际指向/proc/self/fd。里面存放的是某个program所打开的文件描述符。不同的program所看到的/proc/self/fd不同。比如同一个账号在不同tty登录同一台服务器,a看到的/proc/self/fd实际是/proc/8231/fd,而b看到的是/proc/14133/fd

2. /dev/fd里放的是文件描述符。默认的文件描述符有3个,0: stdin;1: stdout; 2: stderr。不同的program打开的文件描述符可能还不同。

3. 当一个文件描述符被关闭后再被试图读写,就会报错。


0 0