0

I'm trying to implement a feature to pipe commands in a basic shell I'm writing. So far I can execute single commands and I've looked around for samples of how to pipe commands but I'm not sure how to implement it in my code. I want to be able to execute single commands as well as pipe commands when necessary and I'm not sure where those modifications need to be made.

I've tried splitting commandexec() into 2 separate functions, one for the source and another for the destination but then I wasn't sure how to execute a single command (no piping). I have this code available too if that would be a better starting point.

Here is my original code:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>

/*Function Prototypes*/
void commandparser(char *line, char **argv);
int commandexec(char **argv);

int main()
{
    char line[1000]; //input line
    char *argv[25]; //command line arguments

    while (1) //repeat until finished
    {
        printf("Shell: "); //the prompt that will be displayed
        if(fgets(line, 1000, argv) == NULL)//read commands and break if there is nothing
        {
            break;
        }
        printf("\n");

        commandparser(line, argv);

        if(commandexec(argv) == 0) //execute the command
        {
            break;
        }

        if (strcmp(argv[0], "exit") == 0) //check if user wants to exit
        {
            exit(0); //exit
        }
    }
}

void commandparser(char *line, char **argv)
{
    const char *delimeter = " "; //where to split the commands
    int i = 0;
    for(; i < argv; i++)
    {
        argv[i] = strtok(&line, delimeter); //split commands by delimeter

        if(argv[i] == NULL)//if there are no commands then it breaks
        {
            break;
        }
    }
}

int commandexec(char **argv)
{
    pid_t pid = fork(); //fork process
    int child;

    if (pid == 0) //begins the child process
    {
        execvp(argv[0], argv); //this will execute the command

        char *err = strerror(errno);
        printf("Shell: %s %s\n", argv[0], err); //error message

        return 0;
    }
    else if (pid == -1) //checks for error
    {
        char *err = strerror(errno);
        printf("%s\n", err);

        return 1;
    }
    else
    {
        waitpid(pid, &child, 0); //this will wait for child to finish

        return 1;
    }
}
donut juice
  • 257
  • 6
  • 19
  • There are a ton of essentially identical questions showing in the right bar under "Related" too. Have you read any of them? – ShadowRanger Feb 11 '16 at 23:42
  • @ShadowRanger checking them out now. Sorry for the ignorant post, was too eager to receive help – donut juice Feb 11 '16 at 23:47
  • You need to use dup2 system call. An example is here. http://stackoverflow.com/questions/7549637/stream-redirection-and-pipes-when-making-a-linux-shell – Umamahesh P Feb 12 '16 at 00:14

0 Answers0