I'm writing a Unix shell, and I spent a ton of time on this function but I cannot get it to work.
Here's where it's messing up:
Code:
// If no slash
if(strchr(token, '/') == NULL)
{
printf("if no slash token %s\n", token);
// Get the path
path = getenv("PATH");
currentToken = strtok(path, colon);
// For every possible path
while(currentToken != NULL)
{
printf("path is %s\n", path);
printf("current token is %s\n", currentToken);
// Add a / and null to the end of it
stringSize = strlen(currentToken);
char buffer[stringSize+2+strlen(token)];
strcpy(buffer, currentToken);
strcat(buffer, "/");
strcat(buffer, token);
strcat(buffer, "\0");
printf("current token before if %s\n", currentToken);
printf("buffer is %s\n", buffer);
// See if this path exists
if(stat(buffer, &pathExists) == 0)
{
printf("if statement");
return runCommand(buffer, argList);
}
currentToken = strtok(NULL, colon);
printf("current token at end of while: %s\n", currentToken);
}
}
I'm trying to get the external commands working, but it only works the first time around, then thinks the currentToken is null after the currentToken = strtok(NULL, colon) statement. Here is sample output:
user@myshell:/home/class/user/course/proj1> ls
token_ptr is ls
if no slash token ls
path is /home/class/user/.bin
current token is /home/class/user/.bin
current token before if /home/class/user/.bin
buffer is /home/class/user/.bin/ls
current token at end of while: /home/class/user/.scripts
path is /home/class/user/.bin
current token is /home/class/user/.scripts
current token before if /home/class/user/.scripts
buffer is /home/class/user/.scripts/ls
current token at end of while: /usr/bin
path is /home/class/user/.bin
current token is /usr/bin
current token before if /usr/bin
buffer is /usr/bin/ls
current token at end of while: /usr/local/java/bin
path is /home/class/user/.bin
current token is /usr/local/java/bin
current token before if /usr/local/java/bin
buffer is /usr/local/java/bin/ls
current token at end of while: /usr/lang
path is /home/class/user/.bin
current token is /usr/lang
current token before if /usr/lang
buffer is /usr/lang/ls
current token at end of while: /bin
path is /home/class/user/.bin
current token is /bin
current token before if /bin
buffer is /bin/ls
if statementtoken is /bin/ls
makefile myshell.c myshell.o proj1submit.sh
makefile~ myshell.c~ myshell.x test
user@myshell:/home/class/user/course/proj1> ls
token_ptr is ls
if no slash token ls
path is /home/class/user/.bin
current token is /home/class/user/.bin
current token before if /home/class/user/.bin
buffer is /home/class/user/.bin/ls
current token at end of while: (null)
What am i doing wrong? It works beautifully the first time!