我正在尝试使用 wait4
为 fork
的进程计时,但是对于 stime
和时间
。我已经验证该进程正在被正确地 fork
,exec
被正确地处理,并且 usage 值是合理的 (>0
)当我 exec
一个测试进程时,它只占用几秒钟的时钟周期。
我怀疑正在使用的时钟的分辨率不足以为短过程正确计时,但是 a) 对于所有查询的 clockid_t
类型,我得到了 1ns
的响应, 和 b) 我看不到任何方法来指定 wait4()
应该使用哪个时钟。
这是我的代码:
double spawnprocess(char *arg1, char *arg2){
struct rusage usage;
struct timeval time;
double t1 = 0.0;
int nogo;
pid_t pid;
char* args[] = { "/path/to/process", arg1, arg2, (char *) 0 };
do {
pid = fork();
if (pid == -1) { printf("Error forking... trying again.\n"); sleep(1); }
} while (pid == -1);
if (pid == 0) {
if ((nogo=execv(args[0], args)) == -1) printf("Error starting new process.\n");
} else {
printf("Waiting for child %d...\n", pid);
int status;
int options = 0;
pid_t cpid = wait4(pid, &status, options, &usage);
if (cpid != pid) {
printf("Error: %d\n", cpid);
int tmp;
if (WIFEXITED(status)) printf("%s", "WIFEXITED");
if ((tmp = WEXITSTATUS(status))) printf("WEXITSTATUS: %d", tmp);
if (WIFSIGNALED(status)) printf("%s", "WIFSIGNALED");
if ((tmp = WTERMSIG(status))) printf("WTERMSIG: %d", tmp);
if (WCOREDUMP(status)) printf("%s", "Core dumped.");
if (WIFSTOPPED(status)) printf("%s", "WIFSTOPPED");
if (WSTOPSIG(status)) printf("%s", "WSTOPSIG");
if (WIFCONTINUED(status)) printf("%s", "WIFCONTINUED");
} else {
t1 = (usage.ru_utime.tv_sec + (usage.ru_utime.tv_usec/1000000.0));
}
}
printf("Sent value is: %e\n", t1);
return t1;
}
最佳答案
系统计时器可能具有纳秒分辨率,但您需要一个专为实时操作而设计的系统,以充分避开您的视线,以便您可以看到那种计时分辨率。我在这里的非 Linux 系统上试过你的代码。在 Pentium III 上运行的旧 FreeBSD 系统有时会打印 0 ,有时会打印 4e-03 。更新的 PowerPC 和 Intel Mac 打印的数字在 4e-05 到 2e-04 范围内。
关于C fork(), wait4() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8783461/