-1

I've been trying to run command using exevp as follows:

char *args[11];
args[0] = (char*)lgulppath.c_str();
args[1] = (char*)"-i";
args[2] = (char*)sniffer_interface.c_str();
args[3] = (char*)"-r";
args[4] = (char*)pcapfileLimit.c_str();
args[5] = (char*)"-C";
args[6] = (char*)"1";
args[7] = (char*)"-f";
args[8] = (char*)serverip_filter.c_str();
args[9] = (char*)"-o";
args[10] = (char*)lpipepath.c_str();
execv("/usr/sbin/program",args);

this works. HOWEVER, when I want to have the first parameter "/usr/sbin/program" as a parameter say:

string str = "/usr/sbin/program";
//char* args is assigned as above
execv(str.c_str(),args);

this fails and returns -1. I CAN'T GET WHY THOUGH.

Thanks everybody

Alon_T
  • 1,430
  • 4
  • 26
  • 47
  • To start with, the argument array you pass to `execv` should be terminated by an entry pointing to `NULL`. Secondly, when you get an error you can check [`errno`](http://en.cppreference.com/w/cpp/error/errno) for the reason (use [`strerror`](http://en.cppreference.com/w/cpp/string/byte/strerror) or [`perror`](http://en.cppreference.com/w/cpp/io/c/perror) to get/print a readable description). – Some programmer dude Oct 30 '12 at 14:41
  • 1
    You seem to be failing to put a NULL at the end of the args array. That could cause all kinds of trouble -- may or may not be your particular problem here, but better fix that first. – hmakholm left over Monica Oct 30 '12 at 14:43

1 Answers1

3

Null terminate the arguments you pass to execv. Something like

char *args[12];
// other args..
args[11] = (char*) 0;
Duck
  • 26,924
  • 5
  • 64
  • 92
  • @Duck..I don't think the problem is args..after all it would have failed in the first try as well..right? – Alon_T Oct 30 '12 at 17:44
  • @user1432779 Not properly terminating the argument array will lead to _undefined behavior_, which means that anything could happen: It might work; It might not work; Or it might crash. – Some programmer dude Oct 31 '12 at 10:12