basic_shell.c

DownloadView Raw

/**
 * basic_shell.c
 *
 * Demonstrates simple shell functionality using fgets(), strtok(), fork(), and
 * exec().
 *
 * Compile: gcc -g -Wall basic_shell.c -o shell
 * Run: ./shell
 *
 * Usage: enter a command (like ls) and press enter.
 */
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void) {
    while (true) {
        char *line = NULL;
        size_t n = 0;
        getline(&line, &n, stdin);
        char *token = strtok(line, " \t\n");
        char *tokens[1000];
        int i = 0;
        while (token != NULL) {
            tokens[i++] = token;
            token = strtok(NULL, " \t\n");
        }
        tokens[i] = (char *) 0;

        pid_t pid = fork();
        if (pid == 0) {
            printf("Executing: %s\n", tokens[0]);
            execvp(tokens[0], tokens);
        } else {
            int status;
            wait(&status);
        }
        /* Should probably check for an error too? */
    }
    return 0;
}