这些选项之间没有太大区别(除了将文件作为严格选项降低了程序的灵活性).为了比较这两种方法,让我们检查一下,一个魔法实体背后的东西FILE*
:
所以在这两种情况下我们都有一个FILE*
对象,一个文件描述符fd - 一个通往操作系统内核的网关和内核基础设施,提供对文件或用户终端的访问,这应该是(除非libc有一些特殊的初始化程序,用于stdout或内核专门处理文件)用fd = 1).
fopen()
?当bash重定向文件时:
fork() // new process is created
fd = open("file", ...) // open new file
close(1) // get rid of fd=1 pointing to /dev/pts device
dup2(fd, 1) // make fd=1 point to opened file
close(fd) // get rid of redundant fd
execve("a") // now "a" will have file as its stdout
// in a
stdout = fdopen(1, ...)
Run Code Online (Sandbox Code Playgroud)
当您自己打开文件时:
fork() // new process is created
execve("a") // now "a" will have file as its stdout
stdout = fdopen(1, ...)
my_file = fopen("file", ...)
fd = open("file", ...)
my_file = fdopen(fd, ...)
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,主要的bash区别在于文件描述符.