通过C ++确定是否在Linux中安装了程序 [英] Determine via C++ whether a program is installed in Linux

查看:237
本文介绍了通过C ++确定是否在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 并解析其输出。 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来定位可执行文件可能是不明智的。所以你可能应该在你的系统 / 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆