main.c
typedef struct parsed_command {
int argc;
char **argv;
} pc;
pc parse_command(char *command, size_t size) {
pc p = {0};
if (fgets(command, size, stdin) == NULL) {
p.argv = NULL;
return p;
};
command[strcspn(command, "\n")] = '\0';
p.argv = malloc(128 * sizeof(char *));
if (!p.argv)
return p;
char *token = strtok(command, " ");
while (token && p.argc < 127) {
p.argv[p.argc++] = token;
token = strtok(NULL, " ");
}
p.argv[p.argc] = NULL;
return p;
}
int main() {
setbuf(stdout, NULL);
add_builtins();
char raw_command[1024];
while (1) {
printf("$ ");
pc command = parse_command(raw_command, sizeof(raw_command));
if (!command.argv) {
printf("\n");
break;
}
if (!command.argv[0])
continue;
shell_builtin *builtin = hashmap_get(command.argv[0]);
if (builtin) {
printf("builtin command detected\n");
builtin->func(command.argc, command.argv);
free(command.argv);
continue;
printf("after continue 1\n");
}
printf("after continue 2\n");
if (run_program(command.argc, command.argv) == -1) {
printf("%s: command not found\n", command.argv[0]);
}
printf("end of while loop . clearing argv\n");
free(command.argv);
}
return 0;
}
exit.c
int builtin_exit(int argc, char **argv) { exit(0); }
run_program.c
int run_program(int argc, char **argv) {
pid_t pid = fork();
switch (pid) {
case -1: {
perror("failed starting child process");
return -1;
};
case 0: {
execvp(argv[0], argv);
return -1;
};
default: {
waitpid(pid, NULL, 0);
return 0;
};
}
}
seems like if i run any command which doesn’t calls run_program , exit works fine however if i run any command calling run_program where command is not a valid command
, i need to run exit several times before my shell terminates.
My doubt is it’s somewhat related to child process however i’m using waitpid which should wait for child process to finish. hence i’m stuck here
