我正在 Linux 上用 C 语言开发一个控制台应用程序。
现在,它的可选部分(不是必需的)取决于可用的命令/二进制文件。
如果我检查system()
我越来越sh: command not found
作为不需要的输出,并将其检测为存在。那么我该如何检查该命令是否存在呢?
不是重复的从 Bash 脚本检查程序是否存在 https://stackoverflow.com/questions/592620/check-if-a-program-exists-from-a-bash-script因为我使用的是 C,而不是 BASH。
回答有关如何发现该命令是否存在于您的代码中的问题。您可以尝试检查返回值。
int ret = system("ls --version > /dev/null 2>&1"); //The redirect to /dev/null ensures that your program does not produce the output of these commands.
if (ret == 0) {
//The executable was found.
}
你也可以使用popen http://linux.die.net/man/3/popen,读取输出。将其与其他答案中建议的 whereis 和 type 命令相结合 -
char result[255];
FILE* fp = popen("whereis command", "r");
fgets(result, 255, fp);
//parse result to see the path of the bin if it has been found.
pclose(check);
或者使用类型:
FILE* fp = popen("type command" , "r");
结果type
命令有点难解析,因为它的输出根据您要查找的内容(二进制、别名、函数、未找到)而变化。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)