Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert std::vector<char*> to a c-style argument vector arv

I would like to prepare an old-school argument vector (argv) to use within the function

int execve(const char *filename, char *const argv[],char *const envp[]);

I tried it with the stl::vector class:

std::string arguments = std::string("arg1");    
std::vector<char*> argv; 
char argument[128];
strcpy(argument, arguments.c_str());
argv.push_back(argument); 
argv.push_back('\0'); // finish argv with zero

Finally I pass the vector to execve()

execve("bashscriptXY", &argv[0], NULL)

The code compiles but ArgV gets "ignored" by execve(). So it seems to be wrong, what I'm trying. How should I build an argV in a efficient way with c++?

like image 664
Maus Avatar asked Nov 05 '09 20:11

Maus


2 Answers

I think the char[128] is redundant as the string local will have the same lifetime, also, try adding the program as argv[0] like rossoft said in his answer:

const std::string arguments("arg1");    
std::vector<const char*> argv;

argv.push_back("bashscriptXY");
// The string will live as long as a locally allocated char*
argv.push_back(arguments.c_str()); 
argv.push_back(NULL); // finish argv with zero

execve(argv[0], &argv[0], NULL);
like image 76
joshperry Avatar answered Sep 30 '22 11:09

joshperry


Beware that argv[0] is always the name of the command itself. So if you want to pass 1 parameter to a program, you have to fill two elements:

argv[0] should be "bashscriptXY" (or whatever you want...)
argv[1] = "your_argument"

like image 45
rossoft Avatar answered Sep 30 '22 11:09

rossoft