#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>

//global constants
const int NUM_PROGS = 3;
const char *PATHS[3] = {"/bin/pwd", "/bin/ls", "/bin/who"};
const char *ARGS[3] = {"pwd", "ls", "who"};

//forward declaration so main knows about it
int runSubprogram(const char *path, const char *args);

int main() {
  int done = 0;
  int item = 0;
  
  while(!done){
    //print menu
    for(int i = 0; i < NUM_PROGS; i++) {
      printf("%d: %s\n", i, ARGS[i]);
    }
    printf("%d: quit\n", NUM_PROGS);
    printf("Select one: ");
    //read the input
    int total = scanf("%d", &item);

    //check for failure
    if(total != 1 || item < 0 || item > NUM_PROGS){
      fprintf(stderr, "Input failed.\n");
      done = 1;
    }
    else if(item == NUM_PROGS){
      printf("Goodbye!\n");
      done = 1;
    }
    else {
      //run the selected program
      done = runSubprogram(PATHS[item], ARGS[item]);
    }
  }

  return 0; //success
}

int runSubprogram(const char *path, const char *args){
  pid_t pid;

  //Call fork to make a child process (copy of this one)
  // Return value:
  //   < 0 error
  //   == child process
  //   > 0 parent process
  pid = fork();

  if (pid < 0) {  //error case
    fprintf(stderr, "Failed to create child.\n");
    return 1;
  }
  else if (!pid) {  //child case (pid==0)
    //do what the child should do
    execlp(path, args, NULL);
    return 1;
  }
  else {  //parent case
    printf("Child %d begun.\n", pid);
    //wait for the child to finish, and then continue
    pid = wait(NULL);
    printf("Child %d completed.\n", pid);
  }

  return 0;
}