I'm writing a program that uses the cpu power to process some information. The program depends on the CPU cores. If there are 2 cores, the program will fork() twice to create 2 instances of the work and return the results.
#define CORES 4
void worker(int id)
{
// blablabla work here
printf("worker %d\n",id);
printf("[%d] I'm child of %d\n",getpid(),getppid());
}
int main (int argc, const char * argv[])
{
int pid;
for (int i=0; i<CORES; i++)
{
pid = fork();
if (pid == 0) // if child
{
worker(i);
exit(0);
}
else if (pid>0)
{
printf("[%d] Big father here!\n",getpid());
}
else
{
printf("--- Fork problem ---");
}
}
return 0;
}
My questions:
- What can I do so the program only terminates when ALL the child processes are done processing the required information? (i think they're becoming orphans)
- How to count the time it took since the first process started working until the last process terminates