Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write() to stdout and printf output not interleaved?

Tags:

c

printf

stdout

#include <stdio.h>
#define MAXLEN 256

int main() {
  int n;
  char buf[MAXLEN];
  while((n = read(0,buf,sizeof(buf))) != 0){
    printf("n: %d:",n);
    write(1,buf,n);
  }
  return 1;
}

The output of the program (where the first read and first write is typed by the user and echoed by the terminal) is:

read
read
write
write
n: 5:n: 6:

The output of printf comes after pressing Ctrl+D at the standard input and not along with the subsequent reads. Why does this happen?

like image 263
s_itbhu Avatar asked Aug 07 '09 05:08

s_itbhu


People also ask

What is writing to stdout?

Writing to stdout would mean writing to its file descriptor 1 ((of the process in question) which may be anything like a terminal or /dev/null ).

What is standard error in C?

Functions of Stderr in C with Examples. Stderr is the standard error message that is used to print the output on the screen or windows terminal. Stderr is used to print the error on the output screen or window terminal. Stderr is also one of the command output as stdout, which is logged anywhere by default.

How can you print the stderr stream using C?

In NetSim, fprintf(stderr,"") and fprintf(stdout,"") statements are used as per C. fprintf(stdout,"") writes whatever is provided within the quotes to LogFile. txt. fprintf(stderr,""); Prints whatever is provided within the quotes, to the console.


2 Answers

Printf is buffered.

You can force printf to 'flush' its buffer using the fflush call:

#include <stdio.h>
#define MAXLEN 256

int main() {
  int n;
  char buf[MAXLEN];
  while((n = read(0,buf,sizeof(buf))) != 0){
    printf("n: %d:",n);
    fflush(stdout); /* force it to go out */
    write(1,buf,n);
  }
  return 1;
}

In general, printf() being buffered is a good thing. Unbuffered output, particularly to visible consoles that require screen updates and such, is slow. Slow enough that an application that is printf'ing a lot can be directly slowed down by it (especially on the Windows platform; Linux and unixes are typically impacted less).

However, printf() being buffered does bite you if you also fprintf(stderr,) - stderr is deliberately unbuffered. As a consequence, you may get your messages with some printf() missing; if you write to another FILE handle that is also associated with the terminal, and might be unbuffered, make sure you first explicitly fflush(stdout).

like image 88
Will Avatar answered Sep 28 '22 11:09

Will


The manpage for fgets tells me:

It is not advisable to mix calls to input functions from the stdio library with low-level calls to read(2) for the file descriptor associ‐ ated with the input stream; the results will be undefined and very probably not what you want.

So the best solution would be not to to use write and printf on the same descriptor.

like image 42
Kasper Avatar answered Sep 28 '22 11:09

Kasper