tags:

views:

404

answers:

4

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?

+7  A: 

You 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.

http://en.wikipedia.org/wiki/System_(C_standard_library)

http://en.wikipedia.org/wiki/Which_(Unix)

grepsedawk
+1 for suggesting `which`. Fix your Wikipedia links, too.
strager
Fixed the links :)
grepsedawk
+3  A: 

the command which probably is what you want.

Zoredache
This was mentioned in @grepsedawk.myopenid.com's answer.
strager
+2  A: 

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:

Dustin
The code is actually on execvp, not execlp (the NetBSD link was already pointing to execvp); I edited your answer to be what you probably intended (feel free to revert if I got it wrong).
CesarB
@CesarB Thanks for cleaning up after me. :)
Dustin
A: 

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
}
joveha