I’m trying to make my own shell in C, but am having trouble with strtok. I use it to correctly parse out the command and arguments from the input, but I can’t get it to parse the path (it currently segfaults). Once I get the path parsed correctly I should be able to call execlp on each piece and fork processes accordingly. Any insight would be greatly appreciated, code is below. Also feel free to comment on style choices too if you think there is something I could be doing better.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
void parse(char *, char *);
void process(char *, char *, int);
int main(int argc, char *argv[]) {
char *command;
char *path;
char buffer[1024];
command = (char *)malloc(sizeof(char));
path = (char *)malloc(sizeof(char));
int loop = 1;
while(loop == 1){
path = getenv("MYPATH");
if(path == NULL)
path = "/bin#.";
printf("($MYPATH is %s)\n", path);
printf("myshell$ ");
command = fgets(buffer, 1024, stdin);
printf("Buffer: %s", buffer);
printf("Command: %s", command);
if(strcmp(command,"exit\n") == 0 || strcmp(command, "quit\n") == 0){
loop = 0;
printf("Program Terminated\n");
}
parse(command, path);
}
return 0;
}
void parse(char *command, char *path){
char *argv;
int argNum = 0;
argv = strtok(command, " ");
while(argv != NULL){
printf("%s %d\n", argv, argNum);
argv = strtok (NULL, " ");
argNum++;
}
printf("Calling...\n");
process(argv, path, argNum);
printf("Called\n");
}
void process(char *argv, char *path, int argNum){
char *pathPiece;
int pathNum = 0;
pathPiece = strtok(path, "#");
while(pathPiece != NULL){
printf("%s %d\n", pathPiece, pathNum);
pathPiece = strtok(NULL, "#");
pathNum++;
}
}
You’re setting path to point to a read-only memory location, and calling
strtokon it is probably the cause of your problems whenstrtokattempts to tokenize it (i.e. write a null character somewhere inside it).You probably need something like:
and call
strcpylike:and
I strongly suggest you read up on string handling in C.