0

I am working to create a tiny shell in C that can accept multiple commands and pipe them together as needed

I have the below code, it is accepting commands and piping them together but it is quitting my tiny shell after running one command (I beleive an EOF is being returned). I want it to be able to accept many lines of commands.

Any tips/advice would greatly be appreciated!

        int i;
        pid_t children[numberOfCommands - 1];
        pid_t groupId = -1;
        for (i = 1; i < numberOfCommands - 1; i++)
        {
            int pd[2];
            if(pipe(pd) < 0){
                unix_error("Pipe failed");
            }
            pid = fork();
            children[i] = pid;
            if (!pid)
            {
                dup2(pd[1], 1);
                if (execve(argv[cmds[i]], argv, environ) < 0)
                {
                    unix_error("First Execve failed");
                }
            }
            else
            {
                if (i == 0)
                {
                    groupId = pid;
                }
                setpgid(pid, groupId);
            }
            dup2(pd[0], 0);
            close(pd[0]);
            close(pd[1]);
        }
        if (execve(argv[0], argv, environ) < 0) // I believe this is where the EOF is coming from
        {
            unix_error("Second Execve failed");
        }
        for (int j = 0; j < numberOfCommands; j++)
        {
            waitpid(children[j], NULL, 0);
        }
  • See my answer: [fd leak, custom Shell](https://stackoverflow.com/a/52825582/5382650) One thing that you're missing is that [given `a | b | c`], you have to connect `stdin` for `b` to `stdout` for `a`. (i.e.) You have to preserve `pd[1]` from `a` to set it as `stdin` for `b`. You aren't doing that. – Craig Estey Sep 24 '22 at 20:10
  • @CraigEstey Okay that makes sense. So I need to put `int prev = -1;` before the loop and then on each iteration call `dup2(prev,pd[1];` ? – newbie_programmer34575347 Sep 24 '22 at 20:27

0 Answers0