Question

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 to 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: ?????
Was it helpful?

Solution

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; [...]

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top