I have written a small 'daemon' in bash that will switch to the headphones if they are detected, and if not, switch to an external USB speaker with PulseAudio.
What I'm looking for is some way to get notification of changes on the file /proc/asound/card0/codec#0
, just like inotifywait
does on real files (considering files under /proc to be as "pseudo-files").
I find my code a bit insane, because it runs sleep 1
with awk
for the whole day, that is 86400 times a day :)
while sleep 1; do
_1=${_2:-}
_2=$(awk '/Pin-ctls/{n++;if(n==4)print}' '/proc/asound/card0/codec#0')
[[ ${_1:-} = $_2 ]] ||
if [[ $_2 =~ OUT ]]; then
use_speakers
else
use_internal
fi
done
What I'm looking for is something like (this example doesn't work):
codec=/proc/asound/card0/codec#0
while inotifywait $codec; do
if [[ $(awk '/Pin-ctls/{n++;if(n==4)print}' $codec) =~ OUT ]]; then
use_speakers
else
use_internal
fi
done
This way the commands inside the loop would be run only when there are real changes on the $codec
file.
top
and GUI system monitors read a whole lot more than that from/proc
at short intervals. Of course, they probably do it much more efficiently as compiled executables, but the point is: polling for information is a common task. – goldilocks Sep 14 '13 at 12:54/proc
, you can probably trigger your script with a udev rule, which would be pretty ideal. Less ideal is how tedious it can be coming up with udev rules ;) – goldilocks Sep 14 '13 at 16:31udevadm monitor
(while plugging the phones in)? As implied it is not my fav thing to wrestle with. I suppose the node in proc might be something that prompts the kernel to check something it can check, and not to report the state of something it has already been informed about. If the former I guess there wouldn't be a previous event. – goldilocks Sep 14 '13 at 17:14/proc
are generated on demand. There is no generic mechanism for notifying of changes in the reported information. Look in the alsa documentation to see if there's a way to be notified when headphones are plugged in. – Gilles 'SO- stop being evil' Sep 14 '13 at 23:30acpi_listen
? It prints a message when headphone is plugged/unplugged. If you strace it, you can see it's not polling (i.e. it's not insane); most of the time, it's waiting for data on socket /var/run/acpid.socket. That data is presumably coming from acpid, and if you strace that, you can see it's not insane either; most of the time it's waiting in select(), and what wakes it up is input from /dev/input/input12 on plug/unplug. Non-root can't read that directly, but I guess that's what acpid and acpid_listen are for. – Don Hatch Jun 02 '18 at 12:06