Why does the following code snippet close STDOUT?

I’m looking at my professor’s code (provided a template for a previous project) for a command-line random number generator. At the end of the code, he does the following:

int main (int argc, char *argv[]) {
  ...

  if (fclose (stdout) != 0)
    output_errno = errno;

  if (output_errno)
    {
      errno = output_errno;
      perror ("output");
    }

  finalize ();
  return !!output_errno;
}

I’ve never really been certain why. However, now I am faced with designing a UNIX Pipe for another project, and the instructions state:

You may notice your program hanging waiting for input. You must call close on any file descriptors not explictly used in your process. Failure to call close will inform the operating system you are not done with it, and it will never return end-of-file from a read system call.

However, input is not output, so I’m wondering why. Any ideas?

>Solution :

Why does the following code snippet close STDOUT?

If the program is writing output to a file, as happens when standard output is redirected to a file in a shell command, it can fail because a disk is full, because a network volume becomes unavailable or a disk is forcibly unmounted or physically removed by a user, or for other reasons. This is not always made known to the program earlier, as ordinary calls such as printf buffer their output. Calling fclose and checking the result gives the program an opportunity to inform the user that the output was not completely written, by writing a message to the standard error stream and by returning a non-zero exit status to the calling environment (in the return from main).

You may notice your program hanging waiting for input… it will never return end-of-file from a read system call.

Pipes between multiple processes are often created by opening a pipe, forking to create a new process, and closing the read side of the pipe in one process and the write side of the pipe in the other. As long as the write side of a pipe is open in any process, there is a possibility (from the point of view of the operating system), that the process could write data into the pipe, so the operating system keeps any process reading the pipe waiting for potential data. Only when all processes have closed the write side of a pipe will the operating system inform readers that there is no more data.

Leave a Reply