在 C 中使用 fork()

问题描述 投票:0回答:3

我正在编写一个程序,使用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. 如何计算从第一个进程开始工作到最后一个进程终止所花费的时间
c time fork posix cpu-cores
3个回答
6
投票

使用

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

3
投票

要等待子进程完成,您可以使用任何

wait
系列系统调用。如果您使用
wait4
,内核将为您提供有关每个进程消耗了多少 CPU 和挂钟时间的信息。但是,您可能会发现在运行开始和结束时调用
gettimeofday
更容易。


0
投票

实现您想要的功能的一种方法是:编写一个 SIGCHLD 处理程序来递增计数器。 (声明计数器易失,否则可能会发生恶作剧。)然后 sigsuspend() 重复等待 SIGCHLD。当计数器与 CORES 匹配时,终止。

要计时,请在生成工作线程之前调用 time() ,然后在终止之前调用 time() ; difftime(3) 将为您提供以秒为单位的双倍时间差。

© www.soinside.com 2019 - 2024. All rights reserved.