开发者

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开发者_Python百科 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


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 */
};


To wait for the child processes to be finished, you use any of the wait family of system calls. If you use wait4, the kernel will give you information about how much CPU and wall-clock time each process consumed. However, you may find that calling gettimeofday at the beginning and the end of the run is easier.


One way to do what you want: Write a SIGCHLD handler that increments a counter. (Declare the counter volatile or mischief may ensue.) Then sigsuspend() repeatedly waiting on SIGCHLD. When the counter matches CORES, terminate.

To time this, call time() just before spawning the worker threads and then just before termination; difftime(3) will give you the time difference in seconds as a double.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜