gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:08:40 26 4
gpt4 key购买 nike

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

我最感兴趣的是重定向机制。我怀疑该文件是在程序开始时打开的 ./program > file 并在结束时关闭。因此,每次程序输出一些东西时,它应该只是写入一个文件,就像听起来一样简单。是这样吗?那么我想这两个选项在速度方面应该是可比的。

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

最佳答案

这些选项之间没有太大区别(除了将文件作为严格选项会降低程序的灵 active )。为了比较这两种方法,让我们检查一下神奇实体 FILE* 背后的内容:

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

fopen() 相比,bash 重定向如何工作?

当 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, ...)

当你自己打开文件时:

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, ...)

如您所见,bash 的主要区别在于文件描述符。

关于c - 在 bash 中重定向 stdout 与在 c 中使用 fprintf 写入文件(速度),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29700478/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com