simple-shell.c
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#define MAX_LINE 80 /* 80 chars per line, per command */
int main(void) {
char *args[MAX_LINE / 2 + 1]; /* command line (of 80) has max of 40 arguments */
int should_run = 1;
char input[MAX_LINE];
pid_t pid;
int i;
while (should_run) {
printf("osh>");
fflush(stdout);
// Read the input
if (fgets(input, MAX_LINE, stdin) == NULL) {
perror("fgets failed");
continue;
}
// Remove newline character from input
size_t length = strlen(input);
if (length > 0 && input[length - 1] == '\n') {
input[length - 1] = '\0';
}
// Parse the input into arguments
char *token = strtok(input, " ");
i = 0;
while (token != NULL) {
args[i++] = token;
token = strtok(NULL, " ");
}
args[i] = NULL;
// Check if the user entered "exit"
if (args[0] != NULL && strcmp(args[0], "exit") == 0) {
should_run = 0;
continue;
}
// Fork a child process
pid = fork();
if (pid < 0) {
perror("fork failed");
continue;
} else if (pid == 0) {
// Child process
if (execvp(args[0], args) == -1) {
perror("execvp failed");
}
exit(1);
} else {
// Parent process
int background = 0;
if (i > 0 && strcmp(args[i - 1], "&") == 0) {
background = 1;
args[i - 1] = NULL; // Remove '&' from arguments
}
if (!background) {
wait(NULL); // Wait for the child process to complete
}
}
}
return 0;
}
參考:greggagne/OSC9e/ch3/simple-shell.c