Hello, I am trying to write a program with multiple forks, but trying to figure out how to show as single output from all the Childs. In this case, just show total number of primes calculated from each child.
So far, I have created the logic and same child runs in for loop and gives individual output.
I am trying with pipes, but stuck on how to use them here. Also, in below I am doing only with one fork(), but I would like to extend this to perform with multiple forks, so multiple Childs can run. Thanks!
Code:
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdio.h>
#include <math.h>
#define N 100
#define K 5
typedef int bool;
#define FALSE 0
#define TRUE 1
bool chkPrime(long num) {
//<Check prime number logic>
return TRUE;
}
int main() {
pid_t pid;
int status;
pid = fork();
for ( int i=0; i<K; i++) {
if ( pid == 0 ) {
//Inside child
int nextCand = (N/K) * i;
int ulimit = (N/K) * (i+1);
int pCount = 0;
printf("nextCand: %d\n", nextCand);
printf("ulimit: %d\n", ulimit);
while(nextCand < ulimit) {
if(chkPrime(nextCand)) {
//printf("Child isPrime: %d \n", nextCand);
pCount++;
}
else {
//printf("Child not prime: %d \n", nextCand);
}
nextCand +=1;
}
printf("End of Child %d, primes found: %d\n", i, pCount);
}
}
}