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;
}
}