Illegal Argument Execv() Unix C++
So I basically have a vector args with 1 argument per array that I'm trying to pass to an execv() call in unix.
Execv accepts two parameters like so: int execv(const char *path, char *const argv[]);
What's the best way to convert my vector of strings t开发者_JS百科o an array of pointers ? Right now I'm doing the following but when I run it with say, ps -a -f, ps yells at me saying illegal argument. Any help is appreciated.
vector<string> args = tokenize(cmd);
char * arg[args.size()];
for(int j=0; j<args.size();j++)
{
arg[j] = (char*)args[j].c_str();
}
retval = execv(args[0].c_str(), arg);
.
>ps
PID TTY TIME CMD
635 ttys000 0:00.18 -bash
16106 ttys000 0:00.00 ./test cpp
12590 ttys001 0:00.02 -bash
>ps -a
ps: illegal argument: ?????
I think your problem may be that you are neglecting to put a NULL at the end of the array. Try this:
char * arg[args.size()+1];
arg[args.size()] = NULL;
for (int j=0; [...]
The execv functions provide an array of pointers to null-terminated strings that represent the argument list available to the new program. The first argument, by convention, should point to the file name associated with the file being executed. The array of pointers must be terminated by a NULL pointer.
精彩评论