在bash中重定向stdout与使用fprintf(速度)在c中写入文件

thi*_*him 7 c bash printf stdout

我想知道哪个选项基本上更快.

最让我感兴趣的是重定向机制.我怀疑文件在程序开始时打开,./program > file并在最后关闭.因此,每当程序输出一些东西时,它应该只是写入文件,就像听起来一样简单.是这样吗?然后我猜两种选择在速度方面都应该具有可比性.

或者它可能是一个更复杂的过程,因为操作系统必须执行更多操作?

mya*_*aut 5

这些选项之间没有太大区别(除了将文件作为严格选项降低了程序的灵活性).为了比较这两种方法,让我们检查一下,一个魔法实体背后的东西FILE*:

所以在这两种情况下我们都有一个FILE*对象,一个文件描述符fd - 一个通往操作系统内核的网关和内核基础设施,提供对文件或用户终端的访问,这应该是(除非libc有一些特殊的初始化程序,用于stdout或内核专门处理文件)用fd = 1).

与之相比,bash重定向如何工作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区别在于文件描述符.