Reputation: 2095
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
Reputation: 213338
You have two processes reading from the terminal at the same time. It is anybody's guess which process gets the input.
You should not expect consistent behavior if you have two processes reading from the same terminal.
Upvotes: 6
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
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