Mihai Neacsu
Mihai Neacsu

Reputation: 2095

What exactly happens with fork()?

int main(){

    char ch;

    fork();

    cin >> c;
}

After calling fork() I should have 2 exact processes running the same code. Why after running this simple example, I am either asked to enter a character only once, either twice? Shouldn't the system expect 2 inputs every single time I run this program?

>./a.out 
a
>./a.out
a
b
>

Upvotes: 3

Views: 277

Answers (4)

Dietrich Epp
Dietrich Epp

Reputation: 213338

You have two processes reading from the terminal at the same time. It is anybody's guess which process gets the input.

  • If the parent process gets the input first, it exits and returns control to the shell. (Note that this actually causes a repeat of the same situation, with shell and the child process fighting for input.)
  • If the child process gets the input first, it exits but control does not return to the shell untill the parent process exits.

You should not expect consistent behavior if you have two processes reading from the same terminal.

Upvotes: 6

Gargi Srinivas
Gargi Srinivas

Reputation: 939

Include a wait() after fork() and try.

Upvotes: 0

Mallik
Mallik

Reputation: 235

fork() creates a child process.

But which process (among the parent and the newly born child) gets the CPU slice is undetermined. When both the processes are blocked for keyboard input, either the child or the parent can get the input. If the parent gets the token, it reads the input into its variable defined in its address space and exits. And the child never gets a chance to read from the input. And this orphaned child process will then be adopted by the 'root' process (pid=1). See ps output.

And in the other case, where the child gets the token and reads the data and exits, the parent is still alive and hence blocks for input again.

Upvotes: 1

Caleb
Caleb

Reputation: 124997

When fork() is called, the operating system typically copies the entire memory space of the executing program (sort of). Both programs then run. The only differences is that in the "new" process, fork() returns 0, and in the "old" process it returns the process ID of the new process.

The reason that you're only asked for one input is that one of the programs is running in the background. The command-line shell only does I/O for one process at a time.

Upvotes: 2

Related Questions