-
Using execv
Hi all,
I have an array of strings named token declared as follows:
char * token[32];
I'm reading a line of input from the user, parsing the string and making each index of token contain each word input by the user (I removed the \n at the end too)
My goal is to pass the input to the shell so that it can execute the line entered by the user as though the user had typed them directly into the terminal.
I tried to do this as follows:
Code:
execv("/bin/tcsh", token);
but it doesn't work...
Let's say I enter ls somedir as the input, then I print out the values of the initialized indices of my array I can see that
token[0] = ls
token[1] = somedir
so I know that the problem isn't that the array isn't being properly initialized...
any ideas why it doesn't work?
-
Depends what you mean by "doesn't work".
Did you (for example) set
token[2] = NULL;
-
Salem: Yes, I've done that.
Correction: Sorry. the result is actually that the /bin/tcsh/ just executes as though I'd just typed /bin/tcsh directly in a terminal (i.e. it seems to ignore the parameters).
-
Well if tsch is anything like bash, then passing a command line to the shell looks something like this.
Code:
$ ls *.c
foo.c new.c old.c util.c wrapper.c
$ bash -c "ls *.c"
foo.c new.c old.c util.c wrapper.c
So
token[0] would be "-c"
token[1] would be "ls *.c"
token[2] would be NULL
-
Thanks for the help guys. I figured it out and my solution is as follows:
Code:
{
int pid;
switch(pid = fork())
{
case -1:
display("Fork failed during execution of shell handled commands.");
break;
case 0:
//child
token[i] = NULL;
execvp(token[0], token);
break;
default:
//parent
wait(NULL);
}
}