Skip to content

Instantly share code, notes, and snippets.

@djpeach
Last active February 6, 2019 14:49
Show Gist options
  • Save djpeach/dfd5b820855c5392ef0412436dd90be1 to your computer and use it in GitHub Desktop.
Save djpeach/dfd5b820855c5392ef0412436dd90be1 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#define MAX_LINE 80
int main(void) {
char *args[MAX_LINE/2 + 1]; // an array of 41 pointers to character arrays
int should_run = 1;
while(should_run) {
/*
Print out the prompt and flush the buffer
*/
printf("osh > ");
fflush(stdout);
/*
Create a command line to hold arguments
*/
char command[MAX_LINE];
gets(command);
/*
Parse commands and store into args
*/
char *command_ptr;
command_ptr = command;
int arg_index = 0;
args[arg_index] = command_ptr;
arg_index++;
while(*command_ptr != '\0') {
if(*command_ptr == ' ' || *command_ptr == '\n') {
// printf("'%c' is a delimiter, changing it to a \\0\n", *command_ptr);
*command_ptr = '\0'; // replace spaces with nul-terminators so args words will terminate
command_ptr++; // move command_ptr to the next char address
args[arg_index] = command_ptr; // set the next args word address to the command pointer
arg_index++; // move the arg index to the next word
} else {
// printf("'%c' is a not a space, moving to next char address\n", *command_ptr);
command_ptr++; // move the command pointer to the next char address
}
}
int arg_index = 0;
args[arg_index] = &command[0]; // need to point to the address of the first char in command
arg_index++;
for(int i=0; i<strlen(command); i++) {
if(command[i] == ' ' || command[i] == '\n') {
command[i] = '\0';
args[arg_index] = &command[i + 1]; // need to point to the address at command[i + 1]
arg_index++;
}
}
/*
Interpret the command to determine what to do with it
*/
if(strcmp(args[0], "exit") == 0) {
should_run = 0;
} else {
// Run command
pid_t pid;
/* Fork a child process */
pid = fork();
if (pid < 0) { /* Error occurred */
fprintf(stderr, "Fork Failed");
return 1;
}
else if (pid == 0) { /* Child process */
execvp(args[0], args);
}
else {
/* Parent will wait for the child to complete */
wait(NULL);
printf("Child Complete\n");
}
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment