在C shell(Unix)中实现管道

5
基本上,我使用标准的POSIX命令创建了一个shell,我希望能够实现管道功能。目前,它可以正确处理命令,并且可以通过&符号进行后台处理。但是我还需要能够使用|和>>进行管道操作。 例如: cat file1 file2 >> file3 cat file1 file2 | more more file1 | grep stuff
以下是我当前的代码。我也想避免使用“SYSTEM”调用。我知道需要使用dup2,但是我的代码方式有些奇怪,所以我希望有人能告诉我是否可行在这个代码中实现管道?谢谢!我知道dup2被使用了,但是对于如何实现>>和|也感到困惑。
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include <iostream>
#include <stdlib.h> 
#include <stdio.h>

using namespace std;


void Execute(char* command[],bool BG)
{
//Int Status is Used Purely for the waitpid, fork() is set up like normal.
    int status;
    pid_t pid = fork();


    switch(pid)
    {
        case  0:
            execvp(command[0], command);

            if(execvp(command[0], command) == -1)
            {
                cout << "Command Not Found" << endl;
                exit(0);
            }

          default:
            if(BG == 0)
            {
                    waitpid(pid, &status, 0);
//Debug             cout << "DEBUG:Child Finished" << endl;
            }


    }

}


bool ParseArg(char* prompt, char* command[], char Readin[],bool BG)
{

    fprintf(stderr, "myshell>");
        cin.getline(Readin,50);
    prompt = strtok(Readin, " ");
    int i = 0;

    while(prompt != NULL)
    {
        command[i] = prompt;
        if(strcmp(command[i], "&") == 0){
//Debug        cout << "& found";
        command[i] = NULL;
        return true;
    }
//Debug        cout << command[i] << " ";
        i++;
        prompt = strtok(NULL, " ");

    }
    return false;
}

void Clean(char* command[])
{
//Clean Array
        for(int a=0; a < 50; a++)
        {
             command[a] = NULL;
        }
}



int main()
{
   char* prompt;
   char* command[50];
   char Readin[50]; 
   bool BG = false;



   while(command[0] != NULL)
   {

        Clean(command);
       BG = ParseArg(prompt, command, Readin, BG);
       if(strcmp(command[0], "exit") == 0 || strcmp(command[0], "quit") == 0 )
       {
             break;
       }

    else
    {
            Execute(command,BG);
    }

   }

   return 1;

}

3
你为什么试图避免系统调用?是为了可移植性吗?尽量使用符合POSIX标准的系统调用。此外,你的shell是C和C++的奇怪混合体。 - nategoose
2个回答

6
管道和重定向是不同的。要实现重定向(如>>),实际上必须使用dup2。首先,使用适当的标志打开所需的文件(对于>>,它们将是O_WRONLY|O_CREAT|O_APPEND)。其次,使用dup2,使stdout(文件描述符1)成为此新打开fd的副本。最后,关闭新打开的fd。
要创建管道,您需要使用pipe系统调用。阅读其手册页,其中包含示例代码。然后,您还需要使用dup2pipe返回的文件描述符分别设为一个进程的stdin和另一个进程的stdout。

你认为我设计的这个shell方式是否“可行”,还是应该重新设计我的shell? - user475353

5
您应该能够在您的shell中实现管道和输出重定向,但我注意到了一些问题:
  • 您的输入读取、解析和输出代码混合在一起,您可能希望将这些功能分开。
  • strtok不适用于作为shell命令的解析器。它适用于非常简单的命令,但您可能需要寻找或创建一个更好的解析器。像echo "hello world"这样的命令会在当前的解析方法下出现问题。
  • 您可能希望创建一个简单的结构来保存您解析的命令。

以下是一些伪代码,以帮助您入门:

#define MAX_LINE 10000
#define MAX_COMMANDS 100
#define MAX_ARGS 100

// Struct to contain parsed input
struct command
{
    // Change these with IO redirection
    FILE *input; // Should default to STDIN
    FILE *output; // Should default to STDOUT

    int num_commands;
    int num_args[MAX_COMMANDS]; // Number of args for each command
    char* command_list[MAX_COMMANDS]; // Contains the programs to be run
    char* args_list[MAX_COMMANDS][MAX_ARGS]; // The args for each command
    boolean background_task;
    boolean append;
}

int main()
{
    char input[MAX_LINE];

    while (1)
    {
        struct command cmd;

        print_prompt();
        read_input(input);
        parse_input(input, &cmd);
        execute(&cmd);
    }
}

祝您在这个项目中好运!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接