Search code examples
c++printfforkstdoutstdio

Regarding fork system call in linux


Okay I am working with the following C/C++ code in linux:

int main() {
    printf("hello");
    Pid = fork();
    if (pid > 0)
            printf("I’m the parent!");
    else
            printf("I’m the child");
    return 0;
}

Here is my output: program output screenshot

My notes from my CS prof say the following:

After a new child process is created, both processes will execute the next instruction following the fork() system call. Please note that Unix will make an exact copy of the parent's address space and give it to the child. Therefore, the parent and child processes have separate address spaces.

For this reason, I am extremely confused as to why it would not only output the current directory again but also the "hello" again? the only possible reason I could think that it would do this is the line that says it "copies the address space" is simply re-running all the commands before the fork but that doesn't make any sense.


Solution

  • When you use printf, the output is buffered. So, do a fflush or \n right after printf.

    Adding the fflush or \n though forces the buffer to be flushed and outputted to the screen. This happens before the fork and hence is only printed once.

    C99 7.19.2p2

    Whether the last line requires a terminating new-line character is implementation-defined.

    It doesn't define what happens if a terminating new-line character isn't provided. Since the standard doesn't define the behavior, the behavior is undefined.