Files
cos331-hw2/COS331-HW2-PEASE/hw.c
T
2025-03-07 04:09:55 +00:00

68 lines
2.0 KiB
C

// HW2 - COS331
// Nicholas Pease
// 03/06/2025
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#define COMMAND_LENGTH 80
const char *terminal_line = "$ ";
int main(int argc, char *argv[])
{
char *command = malloc(COMMAND_LENGTH);
// while (1)
// {
write(0, terminal_line, sizeof terminal_line); // write to terminal
read(0, command, COMMAND_LENGTH); // read from terminal
char *args[5] = { '\0', '\0', '\0', '\0', '\0' }; // 3 arguments + one program name + NULL
args[0] = command;
int start_vector = 1;
while (*command != '\n') {
if (*command == ' ') {
*command = '\0';
args[start_vector] = command + 1;
start_vector++;
}
command++;
}
*command = '\0'; // For newline
int ret = fork(); // Fork
if (ret) {
wait(NULL);
// continue on the loop
} else {
printf("Getting ready to execute program %s", args[0]);
switch (start_vector) {
case 1: // No parameters just filename
printf("\n");
break;
case 2: // one parameter, no need to loop since commas wont work
printf(" with parameter %s.\n", args[1]);
break;
default: // multiple parameters
printf(" with parameters: ");
for (int i = 1; i < start_vector - 1; i++) {
printf("%s, ", args[i]);
}
printf("%s.\n", args[start_vector - 1]);
break;
}
execv(args[0], args);
// Errored out
printf("Program %s failed to launch. Please ensure the file exists and try again.\n", args[0]);
perror("Failed"); // if fails bomb out and print error
exit(0);
}
// }
}