Is there a POSIX function that works like the which command? That is, I pass it a command name, and it looks in $PATH for executables with that name, and returns the absolute path to the command, if any.
A longer explanation: My POSIX-C application wants to launch a subprocess whose process might be called foo or bar. The first idea I had was something like (ignoring that I need the child’s stdin/stdout/stderr):
system("which foo && foo || which bar && bar");
I don’t like this general approach because this shoves all errors concerning process invocation into the exit code of the child process and the stdout/stderr (which I need as binary streams in my application!).
So it looks like I need to replicate the behavior of which in my application code, to locate the foo or bar executable. Is there a suitable POSIX function, or do you even have a code snippet?
You can use the standard
fork/execpattern, but simply runexectwice. Ifexecfails, you try with the other process.This is probably the easiest way to do it, since by capturing the error code from
exec, you can find out exactly why it failed (becausefoodoes not exist).Alternative: You could also implement
whichyourself in C, which may or may not be less annoying than callingwhichdirectly.