The execvp() function executes the program that is given as an argument. It checks the $PATH variable to find the program. I'm writing something in which I would like to check to see if several programs exist before calling any exec() functions. What's the best way to do this?
views:
404answers:
4You can use getenv to get the PATH environment variable and then search through it.
http://www.opengroup.org/onlinepubs/000095399/functions/getenv.html
You can then use fopen to check for the existence of the specific binary names.
You can also do something like system("which App"). which searches $PATH for you.
glibc's and netbsd's execvp actually tries to exec the command for every element along the path until it succeeds or runs out of path to search. Doesn't leave a lot of room for reuse, but seems good.
In general, for questions like this, I like to go to the source and see what it does. NetBSD's is generally the best read:
Once you have an absolute (canonicalized) pathname, you can use either stat(2) or access(2) to see if the file exists.
With stat:
struct stat st;
if (stat(path, &st)) {
// path doesn't exist
}
With access:
if (access(path, F_OK)) {
// path doesn't exist
}