logoISU  

CS 456 - Systems Programming

Spring 2024

Displaying ./code/shellv3/shellbuiltins.c

#include "shell.h"

char *builtin_str[] = {
  "cd",
  "help",
  "curtime",
  "hello",
  "exit"
};


int (*builtin_func[]) (char **) = {
  &shell_cd,
  &shell_help,
  &shell_curtime,
  &shell_hello,
  &shell_exit
};


int num_builtins() {

  return sizeof(builtin_str) / sizeof(char *);

}


int shell_cd(char **args){

  if (args[1] == NULL) {
      fprintf(stderr, "shell: expected argument to \"cd\"\n");
    } else {
      if (chdir(args[1]) != 0) {
          perror("shell:");
      }
    }
  return 1;

}

int shell_help(char **args){

  printf("Current Builtins\n");

  for (int i = 0; i < num_builtins(); i++) {
    printf("  %s\n", builtin_str[i]);
  }

  return 1;

}

int shell_curtime(char **args){

  time_t curtime = time(NULL);

  char * time_str = ctime(&curtime);
  time_str[strlen(time_str)-1] ='\0';
  printf("%s\n", time_str);

  return 1;

}

int shell_hello(char **args){

  printf("Hello, world!\n");

  return 1;

}


int shell_exit(char **args){
  return 0;
}

int execute(char **args){
  
  int i;

  if (args[0] == NULL) {
    // An empty command was entered.
    return 1;
  }

  for (i = 0; i < num_builtins(); i++) {
    if (strcmp(args[0], builtin_str[i]) == 0) {
      return (*builtin_func[i])(args);
    }
  }

  return launch(args);  

}