Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fork() and output

Tags:

c++

linux

fork

unix

I have a simple program:

int main()
{
    std::cout << " Hello World";
    fork();
}

After the program executes my output is: Hello World Hello World. Why does this happen instead of a single Hello world? I'm guessing that the child process is rerun behind the scenes and the output buffer is shared between the processes or something along those lines, but is that the case or is something else happening?

like image 567
Eumcoz Avatar asked Oct 10 '22 21:10

Eumcoz


People also ask

What is the output of fork ()?

fork() returns 0 in the child process and positive integer in the parent process. Here, two outputs are possible because the parent process and child process are running concurrently. So we don't know whether the OS will first give control to the parent process or the child process.

What does fork () return in C?

RETURN VALUE Upon successful completion, fork() returns 0 to the child process and returns the process ID of the child process to the parent process. Otherwise, -1 is returned to the parent process, no child process is created, and errno is set to indicate the error.

What is fork () used for?

In the computing field, fork() is the primary method of process creation on Unix-like operating systems. This function creates a new copy called the child out of the original process, that is called the parent. When the parent process closes or crashes for some reason, it also kills the child process.

How many times does fork print?

If the fork() system call was successful, both the parent and child process will run concurrently, and this statement will print twice. If the PPID is 1, it means the parent process terminated before the child process.


1 Answers

This isn't quite what you thought originally. The output buffer is not shared - when you execute the fork, both processes get a copy of the same buffer. So, after you fork, both processes eventually flush the buffer and print the contents to screen separately.

This only happens because cout is buffered IO. If you used cerr, which is not buffered, you should only see the message one time, pre-fork.

like image 94
John Humphreys Avatar answered Oct 23 '22 16:10

John Humphreys