linux - execvp:执行 ls 命令时 - 出现错误“ ls: 无法访问 /etc : 没有这样的文件或目录”

发布于 2024-10-01 21:35:46 字数 904 浏览 0 评论 0原文

下面的函数接受一个 char 指针数组,例如: arr[0]: LS arr[1]:-l arr[2]:-a arr[3]:/etc arr[4]:NULL /* 由于 execvp 期望末尾为 NULL */

// 函数调用是 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);
        }
}

执行后我收到消息 -

ls: cannot access /etc
: No such file or directory

The below function takes in a array of char pointers Eg :
arr[0]: ls
arr[1]: -l
arr[2]: -a
arr[3]: /etc
arr[4]:NULL /* Since execvp expects a NULL at the end */

// function call is runCmd(arr);
the function definition is below :

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);
        }
}

After executing I get the message -

ls: cannot access /etc
: No such file or directory

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你穿错了嫁妆 2024-10-08 21:35:46

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

Looks like you are reading in the command and forgetting to strip the trailing newline, causing your ls to try and list the directory "/etc\n".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文