linux文件描述符

threcial 发布于 2026-04-14 20 次阅读


文件描述符(File Descriptor, FD)是系统给打开的文件的编号

编号名称作用
0stdin标准输入
1stdout标准输出
2stderr标准错误

常见用法

输出重定向
[root@centos7 ~]# ls 1>file1
[root@centos7 ~]# cat file1
anaconda-ks.cfg
create-certdb.sh
file1
file2

输入重定向
[root@centos7 ~]# ll < file1
总用量 12
-rw-------. 1 root root 1257 4月  13 18:45 anaconda-ks.cfg
-rwxr-xr-x. 1 root root 1289 10月  1 2020 create-certdb.sh
-rw-r--r--. 1 root root   45 4月  14 10:34 file1
-rw-r--r--. 1 root root    0 4月  13 14:52 file2

标准错误和标准输出放一起
[root@centos7 ~]# ls ./ file5
ls: 无法访问file5: 没有那个文件或目录
./:
anaconda-ks.cfg  create-certdb.sh  file1  file2
[root@centos7 ~]# ls ./ file5 1>file1 2>&1
[root@centos7 ~]# cat file1
ls: 无法访问file5: 没有那个文件或目录
./:
anaconda-ks.cfg
create-certdb.sh
file1
file2

手动创建fd(临时,关闭shell失效)
[root@centos7 ~]# exec 3>>testFile
[root@centos7 ~]# ls -l /proc/$$/fd
总用量 0
lrwx------. 1 root root 64 4月  14 09:24 0 -> /dev/pts/0
lrwx------. 1 root root 64 4月  14 09:24 1 -> /dev/pts/0
lrwx------. 1 root root 64 4月  14 09:24 2 -> /dev/pts/0
lrwx------. 1 root root 64 4月  14 09:38 255 -> /dev/pts/0
l-wx------. 1 root root 64 4月  14 09:24 3 -> /root/testFile
注意,此时是用追加模式创建的,所有重定向到&3的都将以追加模式写入testFile