Search code examples
cexecvp

search for app inside PATH environment in c


I'm trying to execute apps in c by name, before the run I want to find out if the name are legal. is there any way to check in c, and find out if the app exist in the PATH environment?

thanks


Solution

  • Probably the best way to do it is to mimic behaviour of 'which' command as Lunar Mushrooms already suggested.

    Quick look to output of following command

    $ strace which ls
    

    reveals that 'which' simply loops through $PATH entries, concatenates it with command name ('ls' in above example) and calls stat64 on it. It breaks loop if stat64 returns something different than -1 (meaning that file exists). Here's relevant snippet of output from tested command:

    ...
    stat64("/home/mz/bin/ls", 0xbfa84350)   = -1 ENOENT (No such file or directory)
    stat64("/usr/local/sbin/ls", 0xbfa84350) = -1 ENOENT (No such file or directory)
    stat64("/usr/local/bin/ls", 0xbfa84350) = -1 ENOENT (No such file or directory)
    stat64("/usr/sbin/ls", 0xbfa84350)      = -1 ENOENT (No such file or directory)
    stat64("/usr/bin/ls", 0xbfa84350)       = -1 ENOENT (No such file or directory)
    stat64("/sbin/ls", 0xbfa84350)          = -1 ENOENT (No such file or directory)
    stat64("/bin/ls", {st_mode=S_IFREG|0755, st_size=96324, ...}) = 0
    stat64("/bin/ls", {st_mode=S_IFREG|0755, st_size=96324, ...}) = 0
    geteuid32()                             = 1000
    getgid32()                              = 1000
    ...