c - 在c中的PATH环境中搜索应用程序

标签 c execvp

我正在尝试在运行之前按名称执行 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/

相关文章:

c - 我的代码块无法编译

c - 如何将 execvp() 与 grep 一起使用?

c - execvpe argv 需要参数匹配语法帮助

c++ - 这是允许的 : memcpy(dest, src, 0)

c - 覆盖 Lua 中的值分配

c - #define issue 如果它是从 if() block 中调用的

c - 为什么 execvp 或 exec* 系列函数之后的任何内容都不会被执行?

c - 使用 execvp 传递参数

c - 尝试调用 execvp 来运行通过标准输入提供的程序名,但每次调用都失败

c - 如何为 Arm Linux 构建静态版本的 pcap 库