如何检查命令是否可用或存在?
如何检查命令是否可用或存在?
我正在Linux上用C语言开发一个控制台应用程序。
现在它的一个可选部分(不是必需的)依赖于某个命令/二进制文件是否可用。
如果我用system()
检查,我会得到sh: command not found
的不需要的输出,但它会检测到它的存在。那么我应该如何检查这个命令是否存在?
这不是从Bash脚本中检查程序是否存在的重复问题,因为我是用C而不是BASH工作。
如何检查命令是否可用或存在?
有时候我们需要在代码中检查某个命令是否可用或存在,以便根据命令的可用性来进行相应的处理。在Linux或任何POSIX操作系统上,我们可以使用stat(2)函数来检查文件的存在。但是,使用stat函数来搜索文件可能会很困难,因为文件可能安装在非标准位置。不过,由于system()函数使用了$PATH环境变量,所以通过遍历$PATH中的所有路径来搜索文件是相对简单的。
下面是一个简单的示例代码,使用循环和字符串拼接来实现这个功能。
#include#include int main() { char *paths[] = {"/usr/bin", "/usr/local/bin", "/bin"}; // 需要搜索的路径列表 int num_paths = sizeof(paths) / sizeof(paths[0]); for (int i = 0; i < num_paths; i++) { struct stat sb; char *path; asprintf(&path, "%s/foo", paths[i]); // 将路径和文件名拼接起来 if (stat(path, &sb) == 0) { // 使用stat函数检查文件是否存在 printf("Command found at %s\n", path); break; } } return 0; }
上述代码中,我们定义了一个需要搜索的路径列表,然后通过循环和字符串拼接将路径和文件名拼接起来,再使用stat函数来检查文件是否存在。如果文件存在,则输出文件所在的路径,并结束循环。
通过上述方法,我们可以在代码中检查命令是否可用或存在,并根据结果进行相应的处理。这样可以增加代码的健壮性和可靠性。
如何检查命令是否可用或存在?
要回答关于如何使用代码发现命令是否存在的问题,可以尝试检查返回值。
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`来读取输出。将其与其他答案中提到的`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);
或者使用`type`命令:
FILE* fp = popen("type command" , "r");
`type`命令的输出比较难解析,因为它的输出根据你要查找的内容(二进制、别名、函数、未找到)而变化。
`whereis`有时也可以用`where`,但使用`which`可能更好。