I realize the title is confusing, couldn't think of a clearer way to word it. Basically, I am calling a strtok loop inside a strtok loop, but when the inner strtok function returns from runCommand, my first strtok loop stops. It simply exits the loop, even when there are other arguments following the first semicolon. When I don't call runCommand(), it works as expected, and parses through all my commands separated by semicolon.
The goal of this code is to parse a line of commands separated by semicolons, then parse command and command arguments to enter into execvp later. This is the only part I am having trouble with. Here it is:
void parseCommand(char *userLine)
{
if(strchr(userLine, ';'))
{
// Get first token
token = strtok(userLine, ";");
// Loop through all tokens
while(token != NULL)
{
// Make a copy
char *copy = malloc(strlen(token) + 1);
strcpy(copy, token);
runCommand(copy);
free(copy);
printf("process returned!\n");
token = strtok(NULL, ";");
}
}
}
void runCommand(char *token)
{
char *args[20];
char **command = args;
//Tokenize each command based on space
char *temp = strtok(token, " \n");
while (temp != NULL)
{
*command++ = temp;
temp = strtok(NULL, " \n");
}
*command = NULL;
// code for fork and execvp here
}
Can someone explain why runCommand is screwing up my first function's parsing? I REALLY don't understand why it's not working with a copy of my original token. Probably simple, but I've looked at it too long?