Redirecting stdout in bash against writing to file c with fprintf (speed)

I am wondering which option is mostly faster.

What interests me the most is the redirection mechanism. I suspect that the file opens at the beginning of the program ./program > file and closes at the end. Therefore, every time a program outputs something, it should just be written to a file, as simple as it seems. This is true? Then I think that both options should be comparable when it comes to speed.

Or maybe this is a more complex process, since the operating system must perform more operations?

+6
source share
3 answers

There is not much difference between these parameters (except that the file as a strict version reduces the flexibility of your program). To compare both approaches, let him check what remains of the FILE* magic entity:

Thus, in both cases, we have a FILE* object, the file descriptor fd is the gateway for the OS kernel and intranuclear infrastructure, providing access to files or user terminals that should (if libc does not have a special initializer for stdout, or the kernel specifically processes files with fd = 1).

How does bash redirection work compared to fopen() ?

When bash redirects a 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, ...) 

When you open the file yourself:

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

So, as you can see, the basic difference of bash comes down to file descriptions.

+4
source

Yes you are right. The speed will be the same. The only difference in two cases is which program opens and closes the file. When you redirect it using the shell, that shell opens the file and makes the descriptor available as stdout for the program. When the program opens the file, well, the program opens the file. After that, the handle is a file descriptor in both cases, so there should be absolutely no difference in speed.

As a side note, a program that writes to stdout can be used in more general ways. You can, for example, say

 ./program | ssh remotehost bash -c "cat > file" 

which will result in writing the output of the program to file on remotehost . Of course, in this case, the comparison is not like the one you are doing in the question.

+3
source

stdout is a FILE descriptor, fprintf writes to a file descriptor, so the speed will be very similar in both cases. Actually printf("Some string") equivalent to fprintf(stdout, "Some string") . I won’t say it anymore :)

+2
source

Source: https://habr.com/ru/post/985350/


All Articles