Hello,
I'm writing a mini shell in C and have problems with my code that I don't understand.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <signal.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#define maxLine 80
void execute(char**args){
pid_t pid;
if ((pid = fork()) < 0) { perror("fork"); exit(1);}
if (pid == 0){ if (execvp(*args, args) == -1){ perror("executing command\n"); exit(1);}}
else wait(&pid);
}
void parse(char* input, char** args){
int argc = 0; char* delm = " \t\n"; char* token = strtok(input,delm);
while (token != NULL){
args[argc] = token; argc++;
token = strtok(NULL, delm);
} execute(args);
}
int main(){
char buf[maxLine];
char *args[64];
while(1){
printf("Prompt: ");
if (fgets(buf,maxLine, stdin) == NULL) {
printf("\n");
exit(0);
} parse(buf, args);
}
}
This code would work if:
- I remove the the if condition around the excevp call, and move the execute call from the parse to the main. Why, I'd like to know.