0

I'm trying to create a simple shell that supports pipes and file redirects. Here's the execute function I came up with so far:

void execute(std::vector<Command *> cmds)
{
    int inp[2], out[2];
    pipe(inp);
    pipe(out);
    int status, fd = 0;

    for (auto cmd : cmds)
    {
        auto pid = fork();

        if (pid == -1) {
            throw std::runtime_error("Could not fork.");
        } else if (pid == 0) {

            dup2(inp[1], 1);
            if (cmd->redirectout) {
                fd = fileno(fopen(cmd->filename.c_str(), "w"));
                dup2(1, fd);
            }

            dup2(out[0], 0);
            if (cmd->redirectin) {
                fd = fileno(fopen(cmd->filename.c_str(), "r"));
                dup2(0, fd);
            }

            close(inp[0]);
            close(inp[1]);
            close(out[0]);
            close(out[1]);

            if(execvp(cmd->args_char[0], cmd->args_char.data()) < 0) {
                std::cout << "Command not found." << std::endl;
                exit(1);
            }

        } else {

            dup2(out[0], inp[0]);

            dup2(out[1], inp[1]);

            close(inp[0]);
            close(inp[1]);
            close(out[0]);
            close(out[1]);

            while (wait(&status) != pid);
        }
    }
}

When I execute this the program is running but nothing happens. I've been working on this function for days but can't seem to understand the reason. I think the parent process is waiting forever for the child. Can somebody please help me with this?

user1563544
  • 379
  • 3
  • 17
  • Can you be more specific about what command you try, what the expected outcome is, and what the actual outcome is? – chepner Feb 10 '14 at 20:43
  • My program should be capable of getting any number of commands separated by pipes and using redirect. I have specific functions that separate and parse the user input and create "Command" structs that contain the arguments of each command, filename and etc. Right now I'm trying to get my program to execute this "cat in.txt | grep game"; a simple test. The expected outcome is "game", actual - program runs with no output. Ideally, my program must work with any commands separated by pipes and using redirects. If you want I can post the Command struct. – user1563544 Feb 10 '14 at 20:50

0 Answers0