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

我正在尝试编写 shell.但是我的 shell没有执行命令 – ls -l |减.我正在使用execvp.代码如下.
#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实际上是一个shell命令行,它由两个由管道连接的进程组成. execvp()调用只能生成一个进程.

如果要从程序中执行此操作,则必须显式调用shell – 通过使用system()调用或将命令行更改为sh -c’ls -l |减’.你的单词数组应如下所示:

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

[编辑]或者,您可以执行shell在内部执行的操作:生成两个进程并使用管道连接它们.这将涉及使用fork(),pipe(),dup2()和execve()调用.但是,调用shell的工作量要少得多,而且因为交互式程序的数量较少,所以不需要担心性能太高:任何时间不到100毫秒的东西都被认为是瞬时的.

相关文章

1、安装Apache。 1)执行如下命令,安装Apache服务及其扩展包...
一、先说一下用ansible批量采集机器信息的实现办法: 1、先把...
安装配置 1. 安装vsftpd 检查是否安装了vsftpd # rpm -qa | ...
如何抑制stable_secret读取关键的“net.ipv6.conf.all.stabl...
1 删除0字节文件 find -type f -size 0 -exec rm -rf {} ...
## 步骤 1:安装必要的软件包 首先,需要确保系统已安装 `dh...