How to wait until all child processes called by fork() complete?

前端 未结 5 821
北恋
北恋 2020-12-08 03:28

I am forking a number of processes and I want to measure how long it takes to complete the whole task, that is when all processes forked are completed. Please advise how to

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 03:46

    The simplest method is to do

    while(wait() > 0) { /* no-op */ ; }
    

    This will not work if wait() fails for some reason other than the fact that there are no children left. So with some error checking, this becomes

    int status;
    [...]
    do {
        status = wait();
        if(status == -1 && errno != ECHILD) {
            perror("Error during wait()");
            abort();
        }
    } while (status > 0);
    

    See also the manual page wait(2).

提交回复
热议问题