Skip to content
Advertisement

Why only the parent process takes input?

I created a program that forks and asks for input:

void main() {
  int a;
  fork();
  fork();
  printf("Enter: ");
  scanf("%d", &a);
  printf("%d received %dn", getpid(), a);
}

I run it and enter one number:

$ ./mytest
Enter: Enter: Enter: Enter: 42
15317 received 42
$

Why does it appear that only the original parent process gets a number? Why isn’t the output instead e.g.:

$ ./mytest
Enter: Enter: Enter: Enter: 42
15317 received 42
15318 received 42
15319 received 42
15320 received 42
$

Advertisement

Answer

All of the processes accept input. The problem is that only one can do so at a time. Which process is getting the input at any given time is unpredictable.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement