简体   繁体   中英

How to handle pipe channels correctly in order to implement pipe command (similar to pipe command in linux)?

i want to implement a pipe command (similar to this in linux bash ) where it basically works like this: command1 | command2 command1 | command2 : using the pipe character “ | ” will produce a pipe, redirects command1 stdout to its write channel and command2 stdin to its read channel.

or:

command1 |& command2 : using the pipe character “ |& ” will produce a pipe, redirects command1 stderr to the pipe's write channel and command2 stdin to the pipe's read channel.

now command 1 can be either an external command from linux that i run using execv or a built in command that i wrote, and command2 is always an external command

my code is not working correctly, i implemented many commands and they all worked perfect for example (cp, redirection... ), so the base is good in my code, but the pipe is just wrong: for example if the command is : showpid |./parser.exe 1 where parser.exe is a giving file that does parsing on the command, for example here if showpid prints: shell process pid is 12311 , then calling this command showpid |./parser.exe 1 the output should be "shell" , but in my code the output is shell process pid is 12311

the reason the code is not working because i am handling the channels of the pipe and the stdin / stdout wrong ! i tried literally every combination possible i think but something is still wrong !

this is my pipe command implementation:

this is the class of the pipe command:

class PipeCommand : public Command {
private:
    int pipeNum;
    int split;
    string cmd1;
    string cmd2;
public:
    PipeCommand(const char* cmd_line);
    virtual ~PipeCommand() {}
    void execute() override;
};

// the pipe constructor , here i want to extract each command from the right and left side of the pipe from the cmd_line , which  is the command line that i get
// fro example : " showpid | grep 1 "

PipeCommand::PipeCommand(const char* cmd_line):Command(cmd_line) {
    pipeNum = -1;
    isBackground = _isBackgroundComamnd(cmd_line);
    string cmd1 = "", cmd2 = "";
    int split = -1;
    for (int i = 0; i < this->num_args; i++) {
        if (strcmp(args[i], "|") == 0) {
            split = i;
            pipeNum = 1;

            break;
        }

        if (strcmp(args[i], "|&") == 0) {
            split = i;
            pipeNum = 2;
            break;
        }

    }


    for (int i = 0; i < split; i++) {
        cmd1 = cmd1 + args[i] + " ";
    }

    for (int i = split + 1; i < num_args; i++) {
        cmd2 = cmd2 + args[i] + " ";
    }


// the implementation of the pipe command
void PipeCommand::execute() {

    int pipeFd[2];
    int pid;
    pipe(pipeFd);

    pid = fork();
    if (pid == 0) { // child process .

    close(pipeFd[1]);
    dup2(pipeFd[1], pipeNum);


        if (isBuiltInCMD(args[0])) {   // if the command is built in which means i wrote it i run it like this ( this works fine i checked it)
            Command *newCmd = CreateBuiltInCommand(const_cast<char *>(cmd1.c_str()));
            newCmd->execute();
            exit(0);
        } else { // if the command is external than use execv
            const char **argv = new const char *[4];
            argv[0] = "/bin/bash";
            argv[1] = "-c";
            argv[2] = cmd1.c_str();
            argv[3] = nullptr;
            execv(argv[0], const_cast<char **>(argv));
            perror("execvp failed");

        } 
    } else {     // the parent process , basically runs the command2 , which it can be only an external command
        pid = fork();  // we fork again in the parent process

        if (pid == 0)  {      // the child process executes the secomd command using execv

            dup2(pipeFd[0], STDIN_FILENO);


        close(pipeFd[0]); 
        dup2(pipeFd[0], pipeNum); 

            // execute

                const char **argv = new const char *[4];
                argv[0] = "/bin/bash";
                argv[1] = "-c";
                argv[2] = cmd2.c_str();
                argv[3] = nullptr;
                execv(argv[0], const_cast<char **>(argv));
                perror("execvp failed");
                             
        } else {   // the parent process waits 

            waitpid(pid,NULL,0);
            close(pipeFd[1]);
            close(pipeFd[0]);
        }

This code makes the pipe, but I think the problem may be in the Parser.exe program not getting the first word, but all the input.

int main(int argc, char** argv)
{
    int pipes[2] {0};
    int pid {0};

    if (argc < 3) {
        printf ("No file to cat and/or no text to grep.\n");
        return 1;
    }

    pipe (pipes);
    pid = fork();
    if (pid == 0) {
        dup2 (pipes[1], STDOUT_FILENO);
        close (pipes[1]);
        close (pipes[0]);
        execl ("/bin/cat", "/bin/cat", argv[1], nullptr);
    } else {
        int pid = fork();
        if (pid == 0) {
            dup2 (pipes[0], STDIN_FILENO);
            close (pipes[1]);
            close (pipes[0]);
            execl ("/bin/grep", "/bin/grep", argv[2], nullptr);
        } else {
            close (pipes[0]);
            close (pipes[1]);
            waitpid (pid, nullptr, 0);
        }
    }
    
    return 0;
}

It is working but you may have to adapt to your class.

This is my output:

manuel@desktop:~/projects$ ./main sync_client.cpp boost
Going to cat sync_client.cpp
Going to grep for boost
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
      std::cout << "  sync_client www.boost.org /LICENSE_1_0.txt\n";
    boost::asio::io_service io_service;
    boost::system::error_code error = boost::asio::error::host_not_found;
      throw boost::system::system_error(error);
    boost::asio::streambuf request;
    boost::asio::write(socket, request);
    boost::asio::streambuf response;
    boost::asio::read_until(socket, response, "\r\n");
    boost::asio::read_until(socket, response, "\r\n\r\n");
    while (boost::asio::read(socket, response,
          boost::asio::transfer_at_least(1), error))
    if (error != boost::asio::error::eof)
      throw boost::system::system_error(error);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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