How to create a callback for "monitor plugged" on an intel graphics? How to create a callback for "monitor plugged" on an intel graphics? linux linux

How to create a callback for "monitor plugged" on an intel graphics?


As a crude solution, you may be able to poll on sysfs. On my laptop I have:

$ cat /sys/class/drm/card0-LVDS-1/statusconnected$ cat /sys/class/drm/card0-VGA-1/statusdisconnected

I'm guessing this requires kernel DRM and possibly KMS.

To see if you can trigger something automatically, you could run udevadm monitor --property, and watch while you are (dis-)connecting the monitor to see if events are reported.

With my radeon, I get an event the first time I connect a VGA monitor, but no events on subsequent disconnects and reconnects. The event should look something like (using yours as an example):

KERNEL[1303765357.560848] change /devices/pci0000:00/0000:00:02.0/drm/card0 (drm)UDEV_LOG=0ACTION=changeDEVPATH=/devices/pci0000:00/0000:00:02.0/drm/card0SUBSYSTEM=drmHOTPLUG=1DEVNAME=dri/card0DEVTYPE=drm_minorSEQNUM=2943MAJOR=226MINOR=0

Unfortunately there's not a lot to match against, but as long as there's only one video card in the picture that's not too important. Find where udev gets rules from on your system (probably /etc/udev/rules.d/), and create a 99-monitor-hotplug.rules file with:

ACTION=="change", SUBSYSTEM=="drm", ENV{HOTPLUG}=="1", RUN+="/root/hotplug.sh"

udev will then run hotplug.sh when a display is connected. As a test, I put the following in /root/hotplug.sh (don't forget to make this script executable):

#!/bin/shfor output in DVI-I-1 LVDS-1 VGA-1; do        echo $output >> /root/hotplug.log        cat /sys/class/drm/card0-$output/status >> /root/hotplug.logdone

With that, I got an entry in hotplug.log after I connected an external display. Even filtering for ACTION=="change", I still got some events on boot, so you may want to take that into account somehow in your script.


This other answer is on the right path: you want to listen to DRM events from udev.

I've implemented a Python script that runs some code when either USB devices or external displays are (un)plugged. I'm including below a minimal version of that script (untested):

#!/usr/bin/env python3import pyudevdef udev_event_received(device):    ...  # Your code here!context = pyudev.Context()monitor_drm = pyudev.Monitor.from_netlink(context)monitor_drm.filter_by(subsystem='drm')observer_drm = pyudev.MonitorObserver(monitor_drm, callback=udev_event_received, daemon=False)observer_drm.start()# This will prevent the program from finishing:observer_drm.join()

See also:


You have three options:

  1. Poll on a specific entry in sysfs.
  2. Use inotify to detect changes in sysfs.
  3. Use a netlink socket with NETLINK_KOBJECT_UEVENT and listen for a change uevent for the device you want.

In any of the ways mentioned, you're still going to have to poll in one way or another, so I'd just go with the first option.