books/apitue/01/simple_shell.c

45 lines
961 B
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <unistd.h>
char * get_input(char *buffer, size_t buflen) {
printf("$$ ");
return fgets(buffer, buflen, stdin);
}
int main(int argc, char **argv) {
char buf[BUFSIZ];
pid_t pid;
int status;
// Cast to void to prevent compiler warning
(void)argc;
(void)argv;
while(get_input(buf, sizeof(buf))) {
buf[strlen(buf) - 1] = '\0';
if ((pid = fork()) == -1) {
fprintf(stderr, "SHELL: Cant fork: %s\n", strerror(errno));
continue;
} else if (pid == 0) {
execlp(buf, buf, (char *)0);
fprintf(stderr, "SHELL: Cant exec %s: %s\n", buf, strerror(errno));
exit(EX_UNAVAILABLE);
}
// Parent waits
if ((pid = waitpid(pid, &status, 0)) < 0) {
fprintf(stderr, "SHELL: waitpid error: %s\n", strerror(errno));
}
}
exit(EX_OK);
}