我正在尝试在运行之前按名称执行 c 中的应用程序 我想知道这个名字是否合法。有没有 如何检查c中,并查明该应用程序是否存在于PATH环境中?
谢谢
最佳答案
可能最好的方法是模仿“which”命令的行为,正如 Lunar Mushrooms 已经建议的那样。
快速查看以下命令的输出
$ strace which ls
显示“which”只是循环遍历 $PATH 条目,将其与命令名称(上例中的“ls”)连接起来并对其调用 stat64。如果 stat64 返回与 -1 不同的值(意味着该文件存在),它将中断循环。以下是测试命令的相关输出片段:
...
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
...
关于c - 在c中的PATH环境中搜索应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10685434/