Making own shell in C -
i'm trying make own shell in c, having trouble strtok. use correctly parse out command , arguments input, can't parse path (it segfaults). once path parsed correctly should able call execlp on each piece , fork processes accordingly. insight appreciated, code below. feel free comment on style choices if think there 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 %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 point read-only memory location, , calling strtok
on cause of problems when strtok
attempts tokenize (i.e. write null character somewhere inside it).
you need like:
char path[1024];
and call strcpy
like:
strcpy(path, getenv("mypath"));
and
strcpy(path, "/bin#.");
i suggest read on string handling in c.
Comments
Post a Comment