Question

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);
Was it helpful?

Solution

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/)

OTHER TIPS

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

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!

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