c - UNIX shell C 管道的执行

标签 c shell unix command pipe

我的程序应该从终端获取输入并执行命令 例如:“ls”或“ls -l | wc”

{...}

//Split the command and store each string in parameter[]
    parameter[0] = malloc(255);                     //Allocate some space to the first element in the array
    cp = strtok(command, " ");                      //Get the initial string (the command)
    strncpy(parameter[0], cp, 50);
    for(i = 1; i < MAX_ARG; i++)
    {
        parameter[i] = malloc(255);
        cp = strtok(NULL, " ");                 //Check for each string in the array
        parameter[i] = cp;                      //Store the result string in an indexed off array
        if(strcmp(parameter[i], "|") == 0)
        {
            i = MAX_ARG;
            cp = strtok(NULL, " ");
            parameter2[0] = malloc(255);
            strncpy(parameter2[0], cp, 50);
            break;
        }
        if(parameter[i]  == NULL)
        {
            break;
        }
    }

    //Find the second set of commands and parameter
    //strncpy(parameter2[0], cp, 50);
    for (j = 1; j < MAX_ARG; j++)
    {
        parameter2[j] = malloc(255);
        cp = strtok(NULL, " ");
        parameter2[j] = cp;
    }

{...}//这是命令和参数部分的执行:

if (proc1 ==  0)
        {
            close(fd[0]);                           //process1 doenst need to read from pipe
            close(STD_INPUT);                       //prepare for output
            dup(fd[1]);                             //Standard output = fd[1]
            close(fd[1]);
            execvp(parameter[0], parameter);        //Execute the process
        }


 else {
if (proc2 == 0)
            {
                close(fd[1]);
                close(STD_OUTPUT);
                dup(fd[0]);
                close(fd[0]);
                execvp(parameter2[0], parameter2);
            }
            //Parent process
            else
            {
            waitpid(-1, &status, 0);            //Wait for the child to be done
            }
   }

我不确定我做错了什么,因为当我输入“ls -l | wc”时,我收到一条消息“|在目录中找不到”

最佳答案

您可以直接使用 execvp 执行 ls 和 wc,但 | 是 shell 程序的一个功能。所以你真正需要做的是运行 bash,然后将你的命令作为参数传递

execl("/bin/bash","-c",command);

虽然这很微不足道,但似乎您真正应该做的是自己实现 shell。为此,您需要进行一些解析,而不仅仅是使用 strtok 进行简单的标记化。如果这是一项作业,我希望他们能为您提供有关如何执行此操作的明确说明,或者至少您需要能够接受哪些类型的 shell 命令(只是管道?也许是子 shell?)。如果您只是想自己实现这一点,我会首先阅读一些编译器工具,例如 lex and yacc它可以帮助您解析 shell 命令并执行它们。

关于c - UNIX shell C 管道的执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7830160/

相关文章:

c - 这段 C 代码的目的是什么?

linux - 从 Bash 输出中隐藏 "Directory and Bash Directory"

linux - 使用 GPG 密码保护 .GZ 文件

c - 通过尾指针添加到链表,无需 3 级间接

c - ANSI C - 计算字符串指针的大小

bash - 时间命令的自定义格式

linux - 使用变量替换为 sed 并添加

linux - 让 VIM 在保存时添加最后一个新行

c - 比较两个整数数组 a 和 b 的元素的程序,并将数组 c 中位于 a 或 b 中但不在 a 和 b 中的元素存储起来

linux - 将变量的内容写入文件