forkfflushinetdxinetd

Using xinetd/inetd, why should servers call fflush()?


All program on xinetd (which I've read) call fflush(). Why?

For example, Inetd-Wikipedia

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
  const char *fn = argv[1];
  FILE *fp = fopen(fn, "a+");

  if(fp == NULL) 
    exit(EXIT_FAILURE);

  char str[4096];
  //inetd passes its information to us in stdin.
  while(fgets(str, sizeof(str), stdin)) {
    fputs(str, fp);
    fflush(fp);
  }
  fclose(fp);
  return 0;
}

Solution

  • fopen uses buffered input. That is to say that calling fputs will write to the in-memory buffer and will not necessary write the data to disk. Calling fflush forces the output buffer to be written to disk.

    Your sample code is using this pattern so that the file will be written as soon as some data is written over the socket, and you can monitor the file to know what was written.