我正在尝试寻找fork()
系统调用的运行时间。每个子进程需要立即退出,父进程需要在创建下一个子进程之前wait()
每个子进程。我还想使用名为time
的shell内置命令来测量程序的执行时间。
到目前为止,我有这段代码,但不确定我是否做得对。
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int global = 100;
int main(int argc, char** argv)
{
int local = 5;
pid_t pid;
pid = fork();
if (pid < 0) {
fprintf(stderr, "error -- failed to fork()");
return 1;
}
if (pid > 0) {
int child_ret;
waitpid(pid, &child_ret, 0);
printf("parent -- global: %i, local: %i\n", global, local);
printf("parent -- child exited with code %i\n", child_ret);
} else {
global++;
local++;
printf("child -- global: %i, local: %i\n", global, local);
exit (0);
}
}
getrusage
系统调用。 - Kazlocal
和global
对于你的父进程没有改变,但是你的代码看起来是正确的。 - tkauslexit
,而应该调用_exit
。如果你在子进程中调用exit
,它会运行父进程的“退出时”处理器,并且重复运行退出处理器的结果是不可预测的。这在过去曾经导致了严重的安全漏洞,因此不要养成管理进程不当的习惯。 - David Schwartz