Reputation: 345
For a school assignment, I have to make a Unix shell. One of the features that we have to implement is the ability to execute multiple commands from the same line when they are separated by ';'. I'm trying to use strtok to make this happen but for some reason, it only executes the last command (for instance, "ls ; pwd" only executes pwd). Both commands work fine when used individually, but not together. Here's the code involving strtok
const char* s = ";";
char* token = strtok(pinput, s);
while( token != NULL )
{
int argc = get_argc(token);
char** argv = get_argv(argc, token);
parse(argc, argv);
token = strtok(NULL, s);
}
}
I've tested get_argc, get_argv, and parse a bunch and they both seem to work fine. Is there anything that I'm doing wrong in my use of strtok? Thanks.
Upvotes: 1
Views: 6015
Reputation: 157
I don't know what your get_argc() and get_argv() are doing ... so here is something that explains usage of strtok for user input from command line.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// Sample command line => a.out 'ls;pwd;ls;pwd'
// Have to use quotes around your input from command line, due to the
// special character ";" in your input.
int main(int argc, char *argv[])
{
int iLen = strlen(argv[1]);
char *sInput = (char *)malloc((iLen+1) * sizeof(char));
strcpy(sInput, argv[1]);
printf("String => %s\n", argv[1]); // String => ls;pwd;pwd;pwd
char *sSeparator = ";";
char *pToken = strtok(sInput, sSeparator);
while(1)
{
if(pToken == NULL)
break;
printf("Token = %s\n", pToken);
pToken = strtok(NULL, sSeparator);
}
return 0;
}
Upvotes: 1
Reputation: 4037
You can instead take the entire string as input, and then split with ";". As it is school assignment, I would like you to try to code it.
Upvotes: 0