【问题标题】:Execv syscall program not getting arguementsExecv 系统调用程序没有得到争论
【发布时间】:2021-02-18 21:19:50
【问题描述】:

我把这个程序写成更精确的 GNU 时间版本。 这个想法是你用你的程序和可选的一些参数来调用它。程序部分正在运行,但参数未正确传递。

> gcc -o time time.c
> ./time sleep 3
exits right away instead of waiting 3 seconds, sleep is called but doesn't seem to see the args.
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc, char* argv[]) {
    if (argc < 2) {
        printf("./time PROGRAM arg1 arg2 ...\n");
        exit(-1);
    }
    struct rusage result;
    pid_t cpid;
    int id = fork();
    if (id == 0) {
        fclose(stdout);
        fclose(stderr);
        execv(argv[1], argv + 1);
    } else {
        cpid = wait(NULL);
    }
    getrusage(RUSAGE_CHILDREN, &result);
    unsigned long micro_seconds =  result.ru_utime.tv_usec + result.ru_stime.tv_usec;
    micro_seconds += (result.ru_utime.tv_sec + result.ru_stime.tv_sec) * 1000000;
    printf("%lu\n", micro_seconds);
    exit(0);
}

【问题讨论】:

  • 程序部分正在运行..sleep 被调用。你确定吗?你怎么知道execv 不只是失败,因为它看起来与sleep 立即返回相同? execv 需要第一个 arg 是完整路径,它不在您的示例运行中。所以我猜execv 实际上失败了。建议您为execv 调用添加错误检查。
  • 我同意 kaylum 如果您需要错误代码,您可以阅读linux.die.net/man/2/execve
  • @kaylum 已删除,谢谢!

标签: c linux gnu timing


【解决方案1】:

execv 的第一个参数必须是完整路径,而不仅仅是“睡眠”。拨打./time /usr/bin/sleep 3 即可。

【讨论】:

  • 请注意,您也可以使用execvp 代替,它将在通常的 PATH 目录中搜索二进制文件。这样用户就不需要输入完整路径了。
  • 我不太了解堆栈溢出的礼仪,但如果你想发帖,我会接受。这是一个更好的解决方案。这是我修改后的程序,可以使用您的想法按预期工作。 gist.github.com/n8ta/00bd9b735f4b9efe7a031f9a98c9a93b
猜你喜欢
  • 2013-10-09
  • 2019-07-30
  • 1970-01-01
  • 2015-11-15
  • 1970-01-01
  • 2021-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多