I want to execute a script on headphones disconnect but I resent the idea of constant polling of the status when there is already some code executed when it's changed.


In most systems if not all, ACPI can handle this event. To test that:

  1. Run acpi_listen
  2. Unplug & replug headphones, example output: (mic/ears share in same jack on my laptop)

    jack/headphone HEADPHONE unplug
    jack/microphone MICROPHONE unplug
    jack/headphone HEADPHONE plug
    jack/microphone MICROPHONE plug
  3. Put your-script.sh in /etc/acpi/

  4. Add an event trigger file for your script in /etc/acpi/events/

    event=jack/headphone HEADPHONE unplug

    Check the other files there to learn from.

  5. You may need to restart acpid service to reload changed rules in /etc/acpi/events/

    sudo service acpid restart

Reference: man acpid

  • Now I just have to find out how to make dbus work from ACPI scrips, but that's a different question. – int_ua Jun 30 '15 at 17:23
  • 2
    @int_ua you need to write DBUS_SESSION_BUS_ADDRESS environ variable into a file in your homedir with a script started with ~/.config/autostart/dbus.desktop. Then you can run su YOURUSER -c "DBUS_SESSION_BUS_ADDRESS=$(cat ~/.dbus_address) amixer ......." from /etc/acpi/your-script.sh – Germar Jun 30 '15 at 20:54
  • Hey, I wrote a script to show a notification. Followed exactly what you said. My script executes notify-send "Headphones connected" on plug event. BUt it doesn't seem to work. askubuntu.com/questions/877804/… – ptmdevncoder Feb 2 '17 at 16:24

The current version of your script now contains a sleep 0.25 command.

sleep is timer-based so doesn't use any processing cycles while sleeping…

It does use a very tiny bit of CPU to set up the timer, but sleep 1 (sleep 1 second), sleep 60 (sleep for a minute) and sleep 86400 (sleep for a day) all use the same number CPU cycles.

Using ACPI however is the perfect solution as ACPI is event-driven instead of polling-driven.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.