繁体   English   中英

在C中使用fork()

[英]Using fork() in C

我正在编写一个使用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. 我该怎么办,该程序仅在所有子进程处理完所需信息后才终止? (我认为他们正在成为孤儿)
  2. 如何计算从第一个过程开始工作到最后一个过程终止所花费的时间

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

要等待子进程完成,请使用任何wait系列的系统调用。 如果使用wait4 ,内核将为您提供有关每个进程消耗多少CPU和时钟时间的信息。 但是,您可能会发现在运行的开始和结束时调用gettimeofday比较容易。

一种执行所需操作的方法:编写一个增加计数器的SIGCHLD处理程序。 (声明计数器可能会波动或恶作剧。)然后,sigsuspend()反复等待SIGCHLD。 当计数器与CORES匹配时,终止。

为此,请在生成工作线程之前然后在终止之前调用time()。 difftime(3)将以秒为单位的时间差加倍。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM