我試圖找到fork()
系統調用的運行時間。每個子進程需要立即退出,並且在創建下一個子進程之前父進程需要對wait()
。我還想使用名爲time
的shell內置命令來測量程序的執行時間。如何計算C中fork()系統調用的運行時間?
到目前爲止我有這個代碼,但不知道如果我做對了。
#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'系統調用。 – Kaz
代碼是否工作?如果是的話,你應該在codereview.stackexchange.com上發佈。如果代碼不起作用,請準確地說出您的想法:您觀察到什麼錯誤或意外行爲? –
你很可能會感到困惑,因爲'local'和'global'不會改變你的父進程,但是,你的代碼看起來是正確的。 – tkausl