views:

142

answers:

3

I am using execv() to run commands from /bin/ such as 'ls', 'pwd', 'echo' from my c++ program, and I am wondering what value I should provide in argv[0];

const char * path = getPath();
char ** argv = getArgs();

execv(path,argv);
+5  A: 

argv[0] should be the full path of the command that you want to run.

Baget
There is no obligation for it to be the full pathname; indeed, the value does not have to be related to the name of the executable at all. It is convenient if it is, but you absolutely cannot rely on it being the full pathname.
Jonathan Leffler
+12  A: 

argv[0] is supposed to be the program name. It's passed to the program's main function. Some programs differentiate their behavior depending on what string argv[0] is. For example the GNU bash shell will disable some of its features if called using sh instead of bash. Best give it the same value that you pass to path.

In linux, argv[0] is the process name displayed by the top utility (which it probably gets from reading entries in /proc/)

Johannes Schaub - litb
Most shells will run the profile if argv[0] is preceded by a dash, as in '`-sh`' or '`-ksh`'. This also works with 'bash' disguised as 'sh' and as itself. It is how the login process requests shells to run the profile.
Jonathan Leffler
+2  A: 

I know that this is not the answer you're looking for but is there a specific reason why you're doing this? The reason I ask is that most if not all of the actions people normally run with either system() or execv() are available in libraries on either Windows or Unix and are safer, faster and less likely to suffer from circumstantial errors. By that I mean, for example, when the PATH changes and suddenly your code stops working.

If you're passing in a string, either in whole or in part, and running it then you also leave yourself open to a user gaining access to the system by entering a command that could be damaging. E.g. imagine you've implemented a file search using find /home -name and your user types in:

"%" -exec rm {} \;

Ouch!

Robin Welch
It was for a homework assignment where I had to create my own simple shell, and I was required to use evecv();
instanceofTom
Point taken. Not perhaps the best subject matter for a homework assignment. Presumably your tutor is at some point going to cover defensive programming? If not, perhaps you could / should suggest that he / she does? Good luck with it in any case - I wish they'd had stackoverflow when I was at college!
Robin Welch