I'm trying to learn more about Unix and am writing a shell in C. My execute() command replaces the function system(), and it works for commands like ls, clear, etc. However, I can't get it work for the cat command. Rather, the number of error messages doubles every time (see below).
==>cat
==>a
==>error in child==>a
a
a
==>error in child==>a
==>error in child==>a
a
a
==>error in child==>a
==>error in child==>a
==>error in child==>a
==>error in child==>a
a
a
==>error in child==>a
==>error in child==>a
==>error in child==>a
==>error in child==>a
==>error in child==>a
==>error in child==>a
==>error in child==>a
==>error in child==>a
a
a
This is the execute() command. If I use system() anywhere I use execute(), cat works great, but with execute(), it doesn't. In the case where the command inputted is just cat
, then args[0]
is cat
and args[1]
is the null terminator. The length is 1.
int execute (char** args)
{
int status;
pid_t pid;
switch(pid = fork())
{
case -1:
status = -1;
fprintf(stderr, "failed to fork");
break;
case 0:
execvp(args[0], args);
fprintf(stderr,"error in child");
default:
if(!WIFSIGNALED(status) && !WIFEXITED(status))
waitpid(pid, &status, WUNTRACED);
}
return 0;
}
This is how execute() is used in the main() method. The command from the keyboard is stored as a string in cmndbuf (which is declared as char cmndbuf[MAX_BUFFER]
). cmndbuf is then split up and put into the new array called splits.
if (cmndbuf[0]){
char** splits=malloc(sizeof(char*)*MAX_BUFFER + 1);
int i;
char* to_sep=cmndbuf;
for(i=0; i<MAX_ARGS; i++)
{
splits[i] = strsep(&to_sep, " ");
if(splits[i]==NULL) break;
}
execute(splits);
//system(cmndbuf); //this works
free(splits);
}
Thanks guys! :)