在C中使用fork()

and*_*pcg 1 c time posix fork core

我正在编写一个程序,它使用cpu power来处理一些信息.该程序取决于CPU核心.如果有2个内核,程序将fork()两次以创建2个工作实例并返回结果.

#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;

}
Run Code Online (Sandbox Code Playgroud)

我的问题:

  1. 我该怎么办才能使程序只在所有子进程处理完所需信息后终止?(我认为他们正在成为孤儿)
  2. 如何计算自第一个进程开始工作直到最后一个进程终止所花费的时间

Arn*_*anc 6

使用wait()等待孩子结束:

int status;
pid_t pid;

while ((pid = wait(&status)) != -1) {
    // pid just terminated
}

// all children terminated
Run Code Online (Sandbox Code Playgroud)

man 2 wait.

有关测量时间的信息,请参阅gettimeofday():

struct timeval tv = {0};

gettimeofday(&tv, NULL);
Run Code Online (Sandbox Code Playgroud)

struct timeval:

struct timeval {
    time_t      tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds */
};
Run Code Online (Sandbox Code Playgroud)