简体   繁体   English

如何检查显示器是否已插入? (Linux)的

[英]How to check if a monitor is plugged in? (Linux)

This is not a duplicate of other questions as I want to get in done in linux. 这不是我要在linux中完成的其他问题的重复。

I am doing image processing on a development board and for this, I am testing/developing on my laptop. 我正在开发板上进行图像处理,为此,我正在笔记本电脑上进行测试/开发。 In OpenCV, there is imshow() which is used to display the image. 在OpenCV中,有imshow()用于显示图像。 But it will work only if a monitor is there. 但是,只有在有显示器的情况下,它才起作用。 So I want to check if a monitor is present before calling it, so that it will be called when the code is run on PCs and not when it is running on the board. 因此,我想在调用监视器之前检查它是否存在,以便在代码在PC上运行而不是在板上运行时调用它。

How do I get this done? 我该如何完成?

...
...
if(<only-if-monitor-is-present>)
  imshow(img);
...
...

You can try to use xset (user preference utility for X) with -q flag: 您可以尝试将xset (user preference utility for X)-q标志一起使用:

The q option gives you information on the current settings. q选项为您提供有关当前设置的信息。

I've written simple program that uses that command and parses an output: 我编写了使用该命令并解析输出的简单程序:

#include <cstdlib>
#include <iostream>

bool is_monitor_present() {
    int result = system("xset -q | tail -n1 | grep 'Monitor is On'");
    return result == 0;
}

int main() {
    bool found  = is_monitor_present();

    if(found) {
        std::cout << "Monitor is present." << std::endl;
    } else {
        std::cout << "Monitor absent." << std::endl;
    }
}

Execution on the Linux Ubuntu 15.04 on my laptop results with output: 我的笔记本电脑在Linux Ubuntu 15.04上的执行结果如下:

Monitor present. 监视当前。

Same code on my Raspberry with up-to-date-or-almost-up-to-date Raspbian: 在Raspberry上使用最新或几乎最新的Raspbian的相同代码:

xset: unable to open display "" xset:无法打开显示“”

Monitor absent. 监视器不存在。

I do not recommend to use this code on production, but for some tests seems to work fine. 我不建议在生产环境中使用此代码,但对于某些测试来说似乎可以正常工作。 At least at Debians. 至少在Debians。

Here's how to do it: 方法如下:

int MonitorNotPresent = system("xset -q | tail -n1 | grep On");
if(!WEXITSTATUS(MonitorNotPresent))
  imshow(img)

Headers used: 使用的标题:

cstdlib

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM