|
CS 456 - Systems Programming
Spring 2024
|
Displaying ./code/shellv2/shellfunctions.c
#include "shell.h"
void run_shell(void){
//some declarations
char *line;
char **args;
char wd[SIZE];
int status;
do{
printf("%s> ", getcwd(wd, SIZE));
line = readLine();
args = splitLine(line);
status = execute(args);
} while(status);
}
char *readLine(void){
char *line = NULL;
size_t bufsize = 0;
//getline allocates a buffer for us
if(getline(&line, &bufsize, stdin) == -1){
if (feof(stdin)){ //we hit EOF
exit(0);
} else {
perror("readLine");
exit(-1);
}
}
return line;
}
char **splitLine(char *line){
int bufsize = TOKBUF;
int position = 0;
char **tokens = malloc(bufsize * sizeof(char*));
char *token;
if(!tokens){
perror("splitLine: allocation error before while loop");
exit(-1);
}
token = strtok(line, TOKDELIM);
while(token != NULL){
tokens[position] = token;
position++;
if(position >= bufsize){
bufsize += TOKBUF;
tokens = realloc(tokens, bufsize* sizeof(char*));
if(!tokens){
perror("splitLine: allocation error in while loop");
exit(-1);
}
}
token = strtok(NULL, TOKDELIM);
}
tokens[position] = NULL;
return tokens;
}
int launch(char **args){
pid_t pid;
int status;
pid = fork();
if(pid == 0){
//child process
if (execvp(args[0], args) == -1){
perror("execute: Error in Child Process");
}
exit(-1);
} else if (pid < 0){
perror("execute: Error forking");
} else {
//parent process
do {
waitpid(pid, &status, WUNTRACED);
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
return 1;
}
|