在bash中重定向stdout与使用fprintf在C中写入文件(速度) [英] Redirecting of stdout in bash vs writing to file in c with fprintf (speed)

查看:67
本文介绍了在bash中重定向stdout与使用fprintf在C中写入文件(速度)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道哪种选择基本上更快.

I am wondering which option is basically quicker.

最让我感兴趣的是重定向机制.我怀疑文件是在程序的开头打开的.文件,并在最后关闭.因此,每当程序输出某些内容时,就应该将其写入到文件中,就像听起来一样简单.是这样吗?然后,我想这两个选项在速度上应该是可比的.

What interests me the most is the mechanism of redirection. I suspect the file is opened at the start of the program ./program > file and is closed at the end. Hence every time a program outputs something it should be just written to a file, as simple as it sounds. Is it so? Then I guess both options should be comparable when it comes to speed.

也许是更复杂的过程,因为操作系统必须执行更多操作?

Or maybe it is more complicated process since the operating system has to perform more operations?

推荐答案

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

There is no much difference between that options (except making file as a strict option reduces flexibility of your program). To compare both approaches, let's check, what stays behind a magical entity FILE*:

因此,在这两种情况下,我们都有一个 FILE * 对象,一个文件描述符 fd -通往OS内核和内核内部基础结构的网关,提供对文件或文件的访问用户终端,应该这样(除非libc为stdout或内核专门使用一些 special 初始化程序来专门处理fd = 1的文件).

So in both cases we have a FILE* object, a file descriptor fd - a gateway to an OS kernel and in-kernel infrastructure that provides access to files or user terminals, which should (unless libc has some special initializer for stdout or kernel specially handles files with fd = 1).

当bash重定向文件时:

When bash redirects file:

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的主要区别在于文件描述符的混乱.

So as you can see, the main bash difference is twiddling with file descriptors.

这篇关于在bash中重定向stdout与使用fprintf在C中写入文件(速度)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆