Proc – Notify of Changes on a File Under /proc

inotifyproc

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.

Best Answer

What I'm looking for is some way to get notification of changes on the file [in proc]

You can't, because they aren't files. This is not quite a duplicate question, but the answer here explains why.

/proc is a kernel interface. There are no real files there, hence they can't change. Reading from the handles is a request and the data in the file when you read it is a reply to that.

The only way you could simulate something like this would be to read the file at intervals and compare the content to see if the reply from the kernel has changed -- looks like you've already done that.

If you stat procfs files, the atime and the mtime will be the same: for some files it is whenever the stat call was, for others a time from during system boot. In the first case, it will always seem to have changed, in the second, it will never seem to have changed.

Related Question