I must write a command interpreter in C. It must:
- handle command options and parameters
- support commands without options and parameters
- allow redirecting one command to another (for example:
ls -a | wc
) with a max of 3 redirects
We can also assume a fixed maximum of arguments (say MAXARG
).
At this moment I have written this code, but I do not know why some commands do not work (e.g. cd
). Please help me.
#include <stdio.h>
#include <string.h>
#include <unistd.h>
void parse(char *line, char **argv)
{
while (*line != '\0') {
while (*line == ' ' || *line == '\t' || *line == '\n' || *line=='|')
*line++ = '\0';
*argv++ = line;
while (*line != '\0' && *line != ' ' &&
*line != '\t' && *line != '\n')
line++;
}
*argv = '\0';
}
int main(int argc,char *argv[])
{
int child_pid;
char * arg[10];
int child_status;
char str[10];
do
{
printf(">> ");
gets(str);
parse(str,arg);
if(!strcmp(arg[0],"end"))
{
break;
}
child_pid = fork();
if(child_pid == 0)
{
execvp(*arg,arg);
printf("Unknown command\n");
}
else
{
wait(&child_status);
printf("koniec\n");
}
}
while(1==1);
return 0;
}