我正在编写一个程序,使用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;
}
我的问题:
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 */
};
实现您想要的功能的一种方法是:编写一个 SIGCHLD 处理程序来递增计数器。 (声明计数器易失,否则可能会发生恶作剧。)然后 sigsuspend() 重复等待 SIGCHLD。当计数器与 CORES 匹配时,终止。
要计时,请在生成工作线程之前调用 time() ,然后在终止之前调用 time() ; difftime(3) 将为您提供以秒为单位的双倍时间差。