Search code examples
clinuxpathposix

Do what `which` does in bash but in C


What's a linux or posix C function to find the executable the same way Bash looks for an executable when you type it? I think which bash command does the same thing at least very similar. So if I give the function argument "ls" it returns "/bin/ls" for example looking into $PATH on the fly.


Solution

  • I examined the source code of the following commnads. Both functions parse and search the environment variable PATH on their own.

    • which
      char*
      extract_colon_unit (char const* string, int* p_index)
      
    • execlp
      static int
      __execvpe_common (const char *file, char *const argv[], char *const envp[],
                        bool exec_script)
      

    I guess there is no C function to search for commands.