int main(int argc, char *argv[]) {
while (true) {
char command[kMaxCommandLength + 1];
readCommand(command, sizeof(command) - 1);
if (feof(stdin)) break;
char *arguments[kMaxArgumentCount + 1];
int count = parseCommandLine(command, arguments,
sizeof(arguments)/sizeof(arguments[0]));
if (count == 0) continue;
bool builtin = handleBuiltin(arguments);
if (builtin) continue; // it's been handled, move on
bool isBackgroundProcess = strcmp(arguments[count - 1], "&") == 0;
if (isBackgroundProcess) arguments[--count] = NULL; // overwrite "&"
pid_t pid = forkProcess(); if (pid == 0) {
if (execvp(arguments[0], arguments) < 0) {
printf("%s: Command not found\n", arguments[0]);
exit(0);
}
}
if (!isBackgroundProcess) {
waitForChildProcess(pid);
} else {
printf("%d %s\n", pid, command);
}
}
printf("\n");
return 0;
}static bool handleBuiltin(char *arguments[]) {
if (strcasecmp(arguments[0], "quit") == 0) exit(0);
return strcmp(arguments[0], "&") == 0;
}
static pid_t forkProcess() {
pid_t pid = fork();
exitIf(pid == -1, kForkFailed, stderr, "fork function failed.\n");
return pid;
}
static void waitForChildProcess(pid_t pid) {
exitUnless(waitpid(pid, NULL, 0) == pid, kWaitFailed,
stderr, "Error waiting in foreground for process %d to exit", pid);
}