在 C 中使用 fork()
我正在编写一个使用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;
}
我的问题:
- 我该怎么做才能使程序仅在所有子进程处理完所需信息后才终止? (我认为他们正在成为孤儿)
- 如何计算从第一个进程开始工作到最后一个进程终止所花费的时间
I'm writing a program that uses the cpu power to process some information. The program depends on the CPU cores. If there are 2 cores, the program will fork() twice to create 2 instances of the work and return the results.
#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;
}
My questions:
- What can I do so the program only terminates when ALL the child processes are done processing the required information? (i think they're becoming orphans)
- How to count the time it took since the first process started working until the last process terminates
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要等待子进程完成,您可以使用任何
wait
系统调用系列。如果您使用wait4
,内核将为您提供以下信息:每个进程消耗了多少 CPU 和挂钟时间。但是,您可能会发现在开头调用gettimeofday
跑步结束时会更容易。To wait for the child processes to be finished, you use any of the
wait
family of system calls. If you usewait4
, the kernel will give you information about how much CPU and wall-clock time each process consumed. However, you may find that callinggettimeofday
at the beginning and the end of the run is easier.完成您想要的操作的一种方法是:编写一个 SIGCHLD 处理程序来递增计数器。 (声明计数器易失,否则可能会发生恶作剧。)然后 sigsuspend() 重复等待 SIGCHLD。当计数器与 CORES 匹配时,终止。
要计时,请在生成工作线程之前调用 time() ,然后在终止之前调用 time() ; difftime(3) 将为您提供以秒为单位的双精度时间差。
One way to do what you want: Write a SIGCHLD handler that increments a counter. (Declare the counter volatile or mischief may ensue.) Then sigsuspend() repeatedly waiting on SIGCHLD. When the counter matches CORES, terminate.
To time this, call time() just before spawning the worker threads and then just before termination; difftime(3) will give you the time difference in seconds as a double.
使用
wait()
等待子进程终止:请参阅
man 2 wait
。要测量时间,请参阅
gettimeofday()
:<代码>结构时间值:
Use
wait()
to wait for children to terminate:See
man 2 wait
.For measuring the time, see
gettimeofday()
:struct timeval
: