I’ve been struggling with this simple linux shell for hours now, and for some reason I just can’t get the most basic thing working correctly. Something is seriously messed up with how I handle my input or something, because one example of how this shell doesn’t work is the mkdir command. It randomly won’t create a random directory I never tried to create, and every time I do create a directory it manages to create some other ones with random names I obviously didn’t create. Something is messed up and I just have no clue, because I’ve been outputting my final argument array and it looks fine from there. Can someone please take a look at this for me.
#include<stdlib.h>
#include<stdio.h>
#include<sys/types.h>
#include<string.h>
#include<unistd.h>
#include<sys/wait.h>
int main(int argc, char *argv[]){
while(1){
char line[100], *temp, *split[15];
int child_id;
printf("$ ");
fgets(line, sizeof(line), stdin);
line[strlen(line)-1] = '\0';
temp = strtok(line, " ");
int i = 0;
while(temp != NULL){
split[i] = temp;
temp = strtok(NULL, " ");
i++;
}
char *args[i];
int j;
for(j = 0; j < i; j++){
args[j] = split[j];
printf("%s\n", args[j]);
}
child_id = fork();
if(child_id == 0){
execvp(args[0], args);
exit(0);
}else{
wait(&child_id);
}
}
}
When using
execvp(), the final element of theargsarray must beNULL(this tells the kernel where the list of command line arguments ends).You should be able to do this by adding
split[i] = NULL;after thestrtok()loop (oh, and no need to copy the array toargsas mentioned in the comment above, just usesplit).