I'm new to C and created this shell to test my knowledge. It takes input from stdin, checks whether the full path has been given, if not, appends input to /bin/ and then executes. How can I improve; what are your suggestions?
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
// Takes input from stdin
char *read_line(char *buf, size_t sz){
printf("Enter command: ");
if ( fgets(buf, sz, stdin) == NULL ) {
return NULL;
}
buf[strlen(buf) - 1] = '\0';
}
// Splits input from stdin
void split(char *buf, char **split[], size_t max){
char* token = strtok(buf, " \n");
int index = 0;
while(token != NULL){
split[index] = malloc(strlen(token) + 1);
strcpy(split[index], token);
index++;
token = strtok(NULL, " \n");
}
}
int main(){
char userInput[50];
size_t szUI = sizeof(userInput);
char *inputSplit[50];
size_t szIS = sizeof(inputSplit);
memset(inputSplit, 0, szIS);
if ( read_line(userInput, szUI) == NULL ) {
printf("Error: CTRL-D ENTERED");
return 0;
}
split(userInput, inputSplit, szIS);
while(1){
if ( fork() == 0 ) {
// Checks if / is present
if ( strpbrk(inputSplit[0], "/") != 0 ) {
if ( execv(inputSplit[0], inputSplit) == -1 ) {
perror("Error");
return 0;
}
}
// Otherwise / is not present
char tmp[20] = "/bin/";
strcat(tmp, inputSplit[0]);
if ( execv(tmp, inputSplit) == -1 ) {
perror("Error");
return 0;
}
memset(tmp, 0, sizeof(tmp));
exit(0);
}
wait(NULL);
memset(userInput, 0, szUI);
memset(inputSplit, 0, szIS);
char cont[20];
printf("Continue?(y/n) ");
if ( fgets(cont, sizeof(cont), stdin) == NULL ) {
return 0;
}
cont[strlen(cont)-1] = '\0';
if ( strcmp(cont, "y") != 0 ) {
return 0;
}
memset(cont, 0, sizeof(cont));
if ( read_line(userInput, szUI) == NULL ) {
printf("Error: CTRL-D ENTERED \n");
return 0;
}
split(userInput, inputSplit, szIS);
}
}