0

I have the following program:

#include    <sys/types.h>
#include    "ourhdr.h"

int     glob = 6;       /* external variable in initialized data */
char    buf[] = "a write to stdout\n";

int
main(void)
{
    int     var;        /* automatic variable on the stack */
    pid_t   pid;

    var = 88;
    if (write(STDOUT_FILENO, buf, sizeof(buf)-1) != sizeof(buf)-1)
        err_sys("write error");
    printf("before fork\n");    /* we don't flush stdout */

    if ( (pid = fork()) < 0)
        err_sys("fork error");
    else if (pid == 0) {        /* child */
        glob++;                 /* modify variables */
        var++;
    } else
        sleep(2);               /* parent */

    printf("pid = %d, glob = %d, var = %d\n", getpid(), glob, var);
    exit(0);
}

I can't explain the differences found at the exit of the program for the two executions (with and without redirection).

What I understand so far is buffering to printf. When we redirect standard output to a file, however, we get two copies of the printf line. In this second case, the printf before the fork is called once, but the line remains in the buffer when fork is called. This buffer is then copied into the child when the parent’s data space is copied to the child.The second printf,right before the exit,just appends its data to the existing buffer.

The most important question I have is: the difference when writing on the screen(exit the console) and when writing in the pipe?

Nostradamus
  • 172
  • 2
  • 5

1 Answers1

1

When writing to the console the standard C library flushes output buffers at every newline, aka "\n".

With any other device, output is only flushed when the buffer is full.

And you have it correct: fork() duplicates the output buffer.

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131