简体   繁体   English

linux execvp; ls无法访问|,没有这样的文件或目录

[英]linux execvp ; ls cannot access |, No such file or directory

I am trying to code a shell. 我正在尝试编写shell。 But my shell doesn't execute the command - ls -l | 但是我的shell没有执行命令 - ls -l | less. 减。 I am using execvp. 我正在使用execvp。 the code is given below. 代码如下。

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

int main(){
    int pid, status, num, len;
    char str[1000], cwd[100];
    char* word[100];

    getcwd(cwd, sizeof(cwd));

    while(1){
        chdir(cwd);

        printf("%s > ", cwd);

        gets(str);

        pid=vfork();

        if(pid == 0){
            num = 0;
            word[num] = strtok (str, " ");

            while (word[num] != NULL) {
                word[num] = strdup (word[num]);
                len = strlen (word[num]);
                if (strlen (word[num]) > 0)
                    if (word[num][len-1] == '\n')
                        word[num][len-1] = '\0';
                word[++num] = strtok (NULL, " ");
            }

            if(strcmp(word[0], "cd") == 0){
                chdir(word[1]);
                getcwd(cwd, sizeof(cwd));
            }
            else{
                execvp(word[0],word);
            }

            exit(0);
        }
        else{
            wait(&status);
        }
    }

    return 0;
}

ls -l | less ls -l | less is actually a shell command line that consists of two processes connected by a pipe. ls -l | less实际上是一个shell命令行,它由两个由管道连接的进程组成。 The execvp() call can only spawn a single process. execvp()调用只能生成一个进程。

If you want to do this from your program, you must invoke the shell explicitly - either by using the system() call, or by changing the command line to sh -c 'ls -l | less' 如果要从程序中执行此操作,则必须显式调用shell - 通过使用system()调用或将命令行更改为sh -c 'ls -l | less' sh -c 'ls -l | less' . sh -c 'ls -l | less' Your word array should look like this: 你的word数组应如下所示:

word[0] = "sh"
word[1] = "-c"
word[2] = "ls -l | less"
word[3] = NULL

[EDIT] Alternatively, you could do what the shell is doing internally: spawn two processes and connect them with a pipe. [编辑]或者,您可以执行shell在内部执行的操作:生成两个进程并使用管道连接它们。 This would involve using the fork() , pipe() , dup2() and execve() calls. 这将涉及使用fork()pipe()dup2()execve()调用。 However, invoking the shell is much less work, and since less is an interactive program anyway, you don't need to worry about performance that much: anything that takes less than 100 ms is perceived as instantaneous. 然而,调用壳要少得多的工作,因为less是一个交互式程序,无论如何,你不必担心多表现:任何时间小于100毫秒被认为是瞬间的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM