Finding processes using ALSA sound fast

hendry picture hendry · Feb 8, 2009 · Viewed 8.3k times · Source

Currently the way /usr/sbin/alsa in Debian knows the processes using the sound card looks like:

echo $( \
    lsof +D /dev -F rt \
    | awk '/^p/ {pid=$1} /^t/ {type=$1} /^r0x(74|e)..$/ && type == "tCHR" {print pid}' \
    | cut -c 2- \
    | uniq \
)

Which is rather ugly and depends on lsof. I am looking for a POSIX solution without lsof, perhaps using /proc.

    time for i in /proc/*/fd/*; do readlink $i | grep -q /dev/snd/pcm && echo $i | awk -F '/' '{print $3}'; done | uniq

Unfortunately seems to take twice as long as the lsof based snippet above. Can you make it faster, in order to make it a viable replacement?

Update I rewrote the above as:

#!/bin/sh
for i in /proc/[0-9]*/fd/*
do
        if readlink $i | grep -q /dev/snd/pcm
        then
                IFS=/; set -- $i; unset IFS; echo $3
        fi
done

But it seems to have the same performance as my earlier snippet. I suspect grep is the culprit.

Update: I have opened a Debian bug on the topic.

Answer

jfsantos picture jfsantos · Feb 8, 2009

There is an answer for this question on the ALSA FAQ. On my system, using fuser is way faster than using lsof.

fuser -v /dev/snd/*