parameter parameter - 1 year ago 160
Bash Question

Simple shell implementation with C in linux, fork causing infinite loop

I'm trying to implement a simple shell in C and my program is causing an infinite loop and creating a ton of new processes/printing

Myshell>
before the user has a chance to enter in any commands. I can't seem to find a way to prevent this and if anyone could help that would be great! (Didn't paste the
#include
headers at top

int main(int argc, char *argv[]){

char buffer[512];
int *status;
size_t nargs;
pid_t pid;
char delim[] = "\n";

while(1){

pid = fork();
if(pid){

printf("Myshell> ");
fgets(buffer, 512, stdin);
//parse(buffer, argv);

argv[0] = strtok(buffer, delim);
for(argc=1; argv[argc-1]; argc++){
argv[argc] = strtok(NULL, delim);
}

if(!strcmp(argv[0], "exit"))
exit(0);

printf("Waiting for child (%d)\n", pid);
pid = wait(status);
printf("Child (%d) finished\n", pid);
exit(0);
}else{
if(execvp(argv[0], argv)){
printf("error");
exit(1);
}else{
exit(0);
}
}
}

return 0;
}

Answer Source

Because you are reading command into buffer using fgets but not from command line argument So argv[argc] for argc > 1 is wrong - undefined behaviour.

When you don't pass any extra command line argument then argv[0] is your program name and argv[1] is NULL. indexing to argv[] for value more then 1 causes array out of index problem.

Instead of declare argv[] and argc as main function parameter declare within main as formal variable something like:

int argc;
char* argv[MAX]; // max number of argument can be pass to your shell 

One more rectification in your code, change:

int *status;

as

int status;

and accordingly correct

pid = wait(status);

as

pid = wait(&status);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download