【问题标题】:execvp ls: cannot access ' ': No such file or directoryexecvp ls: 无法访问' ': 没有这样的文件或目录
【发布时间】:2019-03-31 21:23:43
【问题描述】:

当我尝试使用 execvp 执行不带参数的 ls 命令时,出现错误:ls: cannot access '': No such file or directory。

我不知道为什么,因为他似乎在寻找一个参数''。

代码是这样工作的:

int main(int argc, char *argv[])
{
    char command[250] = "ls";              
    argvs[0] = command;
    argvs[1] = NULL;
    if (execvp( argvs[0], argvs) == -1 )
       perror("exec failed");

    return 0;
 }

我必须在 execvp 中至少给出一个参数吗?并将其设置为 NULL 或其他一些空终止符?

【问题讨论】:

  • argvs 是什么?
  • argvs 是 execvp 的字符数组。我在最后设置了命令和NULL。
  • argvs is the char array for the execvp 不起作用你需要array of pointers 请提供minimal reproducible example
  • 显示的代码不会编译。

标签: c fork exec ls


【解决方案1】:

如果argvs 声明如下

char *argvs[2]; /* array of pointer */

那么下面的代码应该可以在你的机器上运行

int main(int argc, char *argv[]) {
        char command[250] = "ls";
        char *argvs[2];
        argvs[0] = command;
        argvs[1] = NULL;
        if (execvp( argvs[0], argvs) == -1 )
                perror("exec failed");

        return 0;
}

我必须在 execvp 中至少给出一个参数吗?

来自execvp的手册页

int execvp(const char *file, char *const argv[]); /*its having fixed no of argument */

这意味着您必须为execvp() 提供两个参数。

【讨论】:

  • "char *argvs[3];":为什么 3 会像 2 那样做?
  • 是的@alk true。我认为 Op 可能会给 ls -l 等。
猜你喜欢
  • 2017-02-10
  • 2013-03-31
  • 2016-02-26
  • 1970-01-01
  • 2016-02-16
  • 2013-09-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多