C fork(), wait4() 问题

标签 c linux fork

我正在尝试使用 wait4fork 的进程计时,但是对于 stime时间。我已经验证该进程正在被正确地 forkexec 被正确地处理,并且 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/

相关文章:

c - 结构的指针算法

linux - Electron Linux : . AppImage没有显示图标,而.deb是

c - fork : number of processes created

go - 使用 Golang 启动正在运行的程序的另一个实例的好方法是什么?

c - 编译器是否将内存放置在堆上?

c - 将树节点复制到数组中的段错误

c - 在 C 中查找数组的峰值数

linux - 非阻塞套接字客户端连接

c# - Linux 上的 ClientWebSocket 抛出 AuthenticationException (SSL)

c - for() 循环中的 fork()