简体   繁体   中英

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.

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. 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.

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:

The q option gives you information on the current settings.

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:

Monitor present.

Same code on my Raspberry with up-to-date-or-almost-up-to-date Raspbian:

xset: unable to open display ""

Monitor absent.

I do not recommend to use this code on production, but for some tests seems to work fine. At least at Debians.

Here's how to do it:

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

Headers used:

cstdlib

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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