Recently I've been wanting to know "is process X running? If so what PID or PIDs is it running under?". Running ps piped through grep X is the usual thing. But I got really tired of staring at the extra cruft coming out of ps. I wanted to just see process IDs. So I added some extra filters:
ps auxww | grep $USER | grep X | grep -v grep | sed 's/[[:space:]][[:space:]]*/ /g' | cut -d" " -f2
This returns the PIDs for processes $USER owns with "X" in the ps output. I generally inspect the list and if needed re-run it piped to xargs kill -9:
previous-command-line | xargs kill -9
This works as-is under Linux and places where "ps" supports the "auxww" form which includes the full command line for a process. If probably works as well with the "ps -ef" variant of ps.
The extra parts of the query may deserve some explanation.
| grep $USER
Filters out processes by $USER (me).
| grep X
The critical part for filtering the process by command name or other string of interest.
| grep -v grep
My favorite first optimization: exclude this grep command, I know I don't care about it! Bad of course if X is a string with "grep" in it, or if your username is grep.
| sed 's/[[:space:]][[:space:]]*/ /g'
This sed command is in preparation for the cut about to take place. It replaces sequences of whitespace with a single space, so that space can be used as a delimiter in the cut command. If you know how to make sed understand [[:space:]]+, let me know.
| cut -d" " -f2
This extracts the second "field" of each line treated space as the field delimiter.
That's it. If you know of a decent one-liner in Python or Perl or something else, let me know.
1 comment:
Post a Comment