-->

execve的 - 没有这样的文件或目录?(execve - No such file or dir

2019-06-23 15:15发布

我有一些问题的execve。 我试图做一个外壳,可以发挥作用就像bash shell的,但我与派生的子执行命令的问题。 以下是我有孩子。 cmd是一个char *与用户键入的命令。然而,当我运行这个程序,我从PERROR得到这个错误:

execve error: No such file or directory.

我曾尝试与程序简单LS,它应该使路径=“/斌/ LS”,并执行它(我已确认这是我的ls命令是),但它仍然抱怨。 我究竟做错了什么? 谢谢!

码:

if(pid == 0){

     // Parse the command
     char * word = strtok(cmd, " ");
     char path[128] = "/bin/";
     strcat(path, word);

     // Execute the process
     char * newenvp[] = { NULL };
     char * newargv[] = { path, NULL };
     ret = execve(path, newargv, newenvp);
     if(ret == -1){
        perror("execve error");
     }

     return EXIT_SUCCESS;

}

Answer 1:

我会做的第一件事将是插入:

printf ("[%s]\n", path);

之前调用execve 。 这应该确认该可执行文件是什么,你认为它是。

你的代码看起来不错,只要你送入它的输入是正确的,可执行文件实际上可用的。 例如,下面的完整程序工作正常,在我的Debian框:

#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main (int argc, char *argv[]) {
    if (argc > 1) {
        char * word = strtok (argv[1], " ");
        char path[128] = "/bin/";
        strcat (path, word);

        char * newenvp[] = { NULL };
        char * newargv[] = { path, NULL };
        printf ("[%s]\n", path);
        int ret = execve (path, newargv, newenvp);
        if (ret == -1) {
            perror("execve error");
        }
    }
    return 0;
}

输出,当我运行./testprog ls ,沿着线的东西:

[/bin/ls]
kidsshares.ods  paxwords    birthdays    homeloantracking.gnumeric
shares2011.ods  backup0.sh  development  lexar
accounts.ods    backup1.sh  photos       testprog.c
testprog


Answer 2:

如果你不想通过fileystem手动出差找到正确的二进制文件,有execlp (有附加P)。 从手册页:

execlp(),execvp(),execvpe()函数重复在寻找一个可执行文件,如果指定的文件名不包含斜杠(/)字符的外壳的行动。 该文件要求在PATH环境变量指定的目录路径名的冒号分隔的列表。 如果没有定义这个变量,路径列表默认为当前目录,然后通过confstr(_CS_PATH)返回目录列表。 (此confstr(3)呼叫通常返回值 “/ bin中:在/ usr / bin” 中。)[...]



文章来源: execve - No such file or directory?
标签: c linux execve