I'm trying to write a program that has a single parent process create multiple children in a while loop. For testing I started trying to make only 4 processes (1 parent and its 3 children). But it seems like the children are executing code above the line they were created in, even though there is no recursion (to my knowledge) for them to go back to that line.
Here's what I have right now:
int main() {
time_t start;
time_t end;
int i = 0;
pid_t pid;
start = time(NULL);
printf("Αρχική τιμή δευτερολέπτων %d\n", start);
pid = fork();
printf("%d ", pid);
while (i < 2) {
if (pid > 0) {
fork();
wait();
i++;
}
}
printf("check ");
printf("%d", pid);
if (pid > 0) {
end = time(NULL);
printf("%d\n", end - start);
}
return 0;
}
My output for that is:
Αρχική τιμή δευτερολέπτων 1547394155
29338 check 29338 0
29338 check 29338 0
29338 check 29338 0
29338 check 29338 0
So it seems like printf ("%d ", pid)
is running 4 times, even though there should only be 2 processes running at the time.
wait()
typically requires an argument. otherwise, try addingsleep(9999)
or similar and then usingpstree
or something to inspect how the processes are laid out; the fork/wait/while code is very suspect, and printing from both the parent and children processes may run into buffering issues.pid = fork();
andfork()
the function has three different types of returned values. 1) <0 means an error occurred 2) ==0 means the child process is running 3) > 0 means the parent is running. The code should be checking/handling all three conditionspid = fork(); printf("%d ", pid);
all three conditions from the call tofork()
will be executing thatprintf()
statement (hopefully the error condition is not asserted) so theprintf()
statement will be executed twice. Regarding:fork(); wait();
all three conditions will be executing thewait()
, However, only the parent should be executing thewait()
. The code really needs to be checking the returned values from the C library functions:wait()
andfork()
wait();
will cause a compile problem, because the syntax is:pid_t wait( int *status )
and(int *status)
is not the same as()