I have this small program:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
int orig = 1;
for (int i = 0; (i != 3) && orig; ++i) {
orig = orig && fork();
}
if (orig) {
for (int i = 0; i != 3; ++i) {
wait(NULL);
}
} else {
int num;
scanf("%d", &num);
printf("%d\n", num*num);
}
}
Which is supposed to simply square three numbers that it reads from stdin
, but it does not work as expected. Specifically, it looks like one of the children "hogs" all of the cat
ted input, since the program does roughly this:
2
2
2
to
4
0
0
I think I need to use dup
to fix this, but there is almost nothing on it in our course materials, and all I find on the web is way too complicated for me to understand. How exactly can I make all the processes share stdin
?