在C中使用fork()

ve7v8dk2  于 9个月前  发布在  其他
关注(0)|答案(3)|浏览(102)

我正在写一个程序,它使用CPU的能力来处理一些信息。该程序依赖于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;

}

字符串
我的问题:
1.我该怎么做才能让程序只在所有子进程都处理完所需信息时终止?(我认为它们正在成为孤儿)
1.如何计算从第一个进程开始工作到最后一个进程终止所用的时间

ddrv8njm

ddrv8njm1#

使用wait()等待子级终止:

int status;
pid_t pid;

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

// all children terminated

字符串
请参见man 2 wait
有关时间测量,请参见gettimeofday()

struct timeval tv = {0};

gettimeofday(&tv, NULL);


struct timeval

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

vfhzx4xs

vfhzx4xs2#

要等待子进程完成,您可以使用wait系列的任何系统调用。如果您使用wait4,内核将给予有关每个进程消耗多少CPU和挂钟时间的信息。然而,您可能会发现在运行开始和结束时调用gettimeofday更容易。

sigwle7e

sigwle7e3#

有一种方法可以实现:编写一个SIGCHLD处理程序来递增一个计数器。(decompose计数器volatile或恶作剧可能随之而来。)然后sigsuspend()重复等待SIGCHLD。当计数器匹配CORES时,终止。
要计时,在产生工作线程之前调用time(),然后在终止之前调用; difftime(3)将给予以秒为单位的时间差。

相关问题