basic-shell / shell.c
shell.c
Raw
#define  _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>

#include "shell_helper.h"
#include "tokenize.h"

int main(int argc, char **argv) {
  printf("Welcome to mini-shell.\n");
  // store arguments: input, command (and its length in number of tokens), previous command
  char* in = malloc(MAX_SIZE * sizeof(char));
  char* cmd[MAX_SIZE];
  int cmdlen;
  char prev[MAX_SIZE];
  size_t max_length = MAX_SIZE;
  // the main shell loop
  while (1) {
    printf("shell $ ");
    // use getline to read from input
    ssize_t input_length = getline(&in, &max_length, stdin);
    // if the user presses Ctrl-D (meaning End Of File), exit
    if (input_length == EOF) {
      printf("Bye bye.\n");
      break;
    }
    // call helper to make commands into vector 
    store_cmds(in, cmd, &cmdlen);
    // execute the commands, exiting if one of the commands is "exit"
    if (execute_sequence(cmd, &cmdlen, in, prev) == 1) {
      bye_bye(cmd, &cmdlen);
      break;
    }
    // free the command memory
    free_data(cmd, &cmdlen);
  }
  free(in);
  return 0;
}