通过C ++确定是否在Linux中安装了程序 [英] Determine via C++ whether a program is installed in Linux
问题描述
我想从我的C ++代码中调用一个系统
调用一个Linux程序,但我想先检查该程序是否安装在用户的机器上。
I would like to make a system
call to a Linux program from my C++ code, but I would like to check whether the program is installed on the user's machine first.
在Ubuntu中,我可以使用系统调用(例如 dpkg -s gifsicle $ c $)确定是否安装了与该程序关联的程序包c>并解析其输出。
gifsicle
这里是程序名称。
In Ubuntu, I can determine whether a package associated with that program was installed using a system call like dpkg -s gifsicle
and parse its output. gifsicle
here is the program name.
但是,可能程序(例如 gifsicle
)是从源代码编译的,
However, it's possible that the program (e.g. gifsicle
) was compiled from source and thus does not appear in the Ubuntu package repository.
确定程序(例如 gifsicle
)是否可用的一个好的编程方式是什么系统执行C ++代码?
What's a good programmatic way of determining whether a program (e.g. gifsicle
) is available on the system executing the C++ code?
推荐答案
没有针对Linux的标准软件包管理器, dpkg
肯定是错误的答案。
There is no standard package manager for Linux, so dpkg
is definitely the wrong answer.
出于安全和正确的原因,依靠用户的PATH来定位可执行文件可能是不明智的。所以你可能应该在你的系统$ c $调用中使用完全限定路径(例如
/ usr / bin / gifsicle
For security and correctness reasons, it is probably unwise to rely on the user's PATH to locate an executable. So you probably should already be using the fully-qualified path (e.g. /usr/bin/gifsicle
) in your call to system
.
如果是这样,您的问题的简单答案是:
If so, the easy answer to your question is:
if (access("/usr/bin/gifsicle", X_OK) == 0) {
system("/usr/bin/gifsicle -my -args");
}
else if (errno == EACCESS) {
/* gifsicle not found */
}
else {
/* access() failed! Operating system is broken or Windows (or both) */
}
你把 / usr / bin / gifsicle
放入变量)
更难 - - answer是避免 system
和执行 fork
+ execl
自己,检查 execl
看看是否导致 ENOENT
或类似。将故障传回到父进程可能很烦人。
The harder -- but arguably "more correct" -- answer is to avoid system
and do fork
+ execl
yourself, checking the execl
to see if it results in ENOENT
or similar. Communicating the failure back to the parent process could be annoying, though.
这篇关于通过C ++确定是否在Linux中安装了程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!