Issue
I tried mixing write and printf.
#include <stdio.h>
#include <unistd.h>
main()
{
printf("ca");
write(1, "lu", 2);
}
However, it seems to execute line 8 before line 7.
$ gcc bar.c 2>/dev/null && ./a.out
luca$
I am a beginner in C. I'd like to know what exactly happens here. Thanks!!!
Solution
Nothing is executing out of order. It's just printing out of order.
When you invoke this:
write(1, "lu", 2);
You're telling the operating system to get those two charaters to the console (stdout) immediately. You are bypassing the C runtime for access to stdout.
But... printf
as a member of the standard C library will buffer all the characters passed to it until a \n
(end of line) char is seen. There's some language and unix lawyers that can describe the relationship between \n
and flusing to stdout more precisely.
Generally speaking, fewer I/O operations is a faster program, so buffering has its advantages - especially if stdout is getting redirected to disk.
So to summarize, printf doesn't actually get stuff to the screen until a \n
char is sent to it or until the program is ready to exit. This behavior may vary between platforms and console configurations. printf
will ultimately call write(1,...)
but only after its got a reason to flush its contents.
But when you mix and match printf
and another function that handles its own writing to stdout (console) without end of line chars, these types of unexpected results happen.
Answered By - selbie Answer Checked By - Marie Seifert (WPSolving Admin)