I need to use the fork()
and wait()
functions to complete an assignment. We are modelling non-deterministic behavior and need the program to fork()
if there is more than one possible transition.
In order to try and work out how fork
and wait
work, I have just made a simple program. I think I understand now how the calls work and would be fine if the program only branched once because the parent process could use the exit status from the single child process to determine whether the child process reached the accept state or not.
As you can see from the code that follows though, I want to be able to handle situations where there must be more than one child processes. My problem is that you seem to only be able to set the status using an _exit
function once. So, as in my example the exit status that the parent process tests for shows that the first child process issued 0 as it's exit status, but has no information on the second child process.
I tried simply not _exit()
-ing on a reject, but then that child process would carry on, and in effect there would seem to be two parent processes.
Sorry for the waffle, but I would be grateful if someone could tell me how my parent process could obtain the status information on more than one child process, or I would be happy for the parent process to only notice accept status's from the child processes, but in that case I would successfully need to exit from the child processes which have a reject status.
My test code is as follows:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/wait.h>
int main(void) {
pid_t child_pid, wpid, pid;
int status = 0;
int i;
int a[3] = {1, 2, 1};
for(i = 1; i < 3; i++) {
printf("i = %d
", i);
pid = getpid();
printf("pid after i = %d
", pid);
if((child_pid = fork()) == 0) {
printf("In child process
");
pid = getpid();
printf("pid in child process is %d
", pid);
/* Is a child process */
if(a[i] < 2) {
printf("Should be accept
");
_exit(1);
} else {
printf("Should be reject
");
_exit(0);
}
}
}
if(child_pid > 0) {
/* Is the parent process */
pid = getpid();
printf("parent_pid = %d
", pid);
wpid = wait(&status);
if(wpid != -1) {
printf("Child's exit status was %d
", status);
if(status > 0) {
printf("Accept
");
} else {
printf("Complete parent process
");
if(a[0] < 2) {
printf("Accept
");
} else {
printf("Reject
");
}
}
}
}
return 0;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…