Reputation: 39
I try to create 4 child processes who will work simultaneously, but the output of my program is quite random: sometimes one of the processes is not created (the printf statement is not executed). I can not understand the reason for this, because when I use the wait() function in my parent it should wait for it's children to finish? Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#define NR_OF_PROCESSES 4
void readProcess(void);
void tokenProcess(void);
void calculatorProcess(void);
void errorProcess(void);
void (*functionTable[NR_OF_PROCESSES]) (void) = {readProcess, tokenProcess, calculatorProcess, errorProcess};
int main(void) {
int i;
int status;
for (i = 0; i < NR_OF_PROCESSES; i++) {
int pid = fork();
if (pid < 0) {
perror("could not fork");
return 0;
}
if (pid == 0) {
functionTable[i]();
exit(0);
}
}
printf("parent is waiting");
wait(status);
return (0);
}
void readProcess(void) {
printf("readprocess running, PID=%d, PPID=%d\n",getpid(),getppid());
}
void tokenProcess(void) {
printf("tokenprocess running, PID=%d, PPID=%d\n",getpid(),getppid());
}
void calculatorProcess(void) {
printf("calculatorprocess running, PID=%d, PPID=%d\n",getpid(),getppid());
}
void errorProcess(void) {
printf("errorprocess running, PID=%d, PPID=%d\n",getpid(),getppid());
}
Also, I want to add interprocess communication with pipes later on. Will this be possible if I implement the processes this way? Any better solution?
Upvotes: 1
Views: 105
Reputation: 171263
You only wait for one child, you probably want to call wait for each child.
Upvotes: 1