3 ms·
I like your style, but it's not quite right: $ echo /proc/[0-9]/status | wc 1 7 105 $ echo /proc/[1-9]*/status | wc 1 483
by mzs 3y ago
I like your style, but it's not quite right:
$ echo /proc/[0-9]/status | wc
1 7 105
$ echo /proc/[1-9]*/status | wc
1 483 8778
It also will sporadically print error messages due to all the race conditions. Here's my stab at it:
$ cat dumbps
#!/bin/sh
case $# in
1)
;;
*)
echo "Usage: dumbps user" >&2
exit 2
;;
esac
2>&- find /proc -mindepth 2 -maxdepth 2 -type f -name status -user "$1" | awk '{
while ((getline li < $0) > 0) {
if (li ~ /^Name:/) {
split($0, fn, "/")
print fn[3], substr(li, 6)
break
}
}
close($0)
}'
$ ./dumbps "$USER" | grep -w 'bash$'
1616678 bash
$ ./dumbps 0 | grep -w 'systemd$'
1 systemd
$
It's pretty fast too:
$ ls -ld /proc/[1-9]*/status | awk '$3 == "root"' | wc
445 4005 29367
$ time ./dumbps >/dev/null
Usage: dumdps user
real 0m0.001s
user 0m0.000s
sys 0m0.001s
$
- TristanBall 3y agoYou seem to have very similar races here though? Perfectly possible, even likely, for a process to end between "find" finding it and awk opening it... especially given the pipe buffer between the two. Personly I'd rather an "expect errors" approach.. break it out so that you can easily treat a failed open as a "continue next" scenario and hide just those errors
- mzs 3y ago2>&- hides races in find itself while ((getline li < $0) > 0) hides races in awk in practice Name: is the first line so cmd is not truncated Of course I got my test wrong though :D $ time ./dumbps 0 >/dev/null real 0m0.030s user 0m0.012s sys 0m0.022s