linuux - execvp:执行ls命令 - 获取错误"ls:无法访问/ etc:没有这样的文件或目录"

Ete*_*ner 0 linux fork exec

下面的函数接受一个char指针数组Eg:arr [0]:ls arr [1]: - l arr [2]: - a arr [3]:/ etc arr [4]:NULL/*因为execvp需要最后是一个NULL*/

// function call is runCmd(arr); 函数定义如下:

void runCmd(char *arr[]){

        pid_t child_pid,tpid;
        int child_status;

        child_pid = fork();

        if(child_pid == 0){

                /* The child process executes the exec*/

                execvp(arr[0],arr);

                /*if it returns it must have failed */
                fflush(stdout);
                printf("Unknown Command \n");
                exit(0);
        }
                else {
                /*  let the parent wait for the child */
                do{
                         tpid = wait(&child_status);
                }while(tpid != child_pid);
        }
}
Run Code Online (Sandbox Code Playgroud)

执行后我收到消息 -

ls: cannot access /etc
: No such file or directory
Run Code Online (Sandbox Code Playgroud)

Ark*_*kku 7

看起来您正在读取命令并忘记删除尾随换行符,导致您ls尝试列出目录"/etc\n".