#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
const int NUM_PROGS = 3;
const char *PATHS[3] = {"/bin/pwd", "/bin/ls", "/bin/who"};
const char *ARGS[3] = {"pwd", "ls", "who"};
int runSubprogram(const char *path, const char *args);
int main() {
int done = 0;
int item = 0;
while(!done){
for(int i = 0; i < NUM_PROGS; i++) {
printf("%d: %s\n", i, ARGS[i]);
}
printf("%d: quit\n", NUM_PROGS);
printf("Select one: ");
int total = scanf("%d", &item);
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 {
done = runSubprogram(PATHS[item], ARGS[item]);
}
}
return 0; }
int runSubprogram(const char *path, const char *args){
pid_t pid;
pid = fork();
if (pid < 0) { fprintf(stderr, "Failed to create child.\n");
return 1;
}
else if (!pid) { execlp(path, args, NULL);
return 1;
}
else { printf("Child %d begun.\n", pid);
pid = wait(NULL);
printf("Child %d completed.\n", pid);
}
return 0;
}