Search code examples
ctimeforkposixcpu-cores

Using fork() in C


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:

  1. 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)
  2. How to count the time it took since the first process started working until the last process terminates

Solution

  • Use wait() to wait for children to terminate:

    int status;
    pid_t pid;
    
    while ((pid = wait(&status)) != -1) {
        // pid just terminated
    }
    
    // all children terminated
    

    See man 2 wait.

    For measuring the time, see gettimeofday():

    struct timeval tv = {0};
    
    gettimeofday(&tv, NULL);
    

    struct timeval:

    struct timeval {
        time_t      tv_sec;     /* seconds */
        suseconds_t tv_usec;    /* microseconds */
    };