11

I need the pid for a process given its owner and its command. I can filter a process per user with "ps -u xxx" and its command by "ps -C yyy", but when I try "ps -u xxx -C yyy", they are combined using OR logic. I need AND logic. How can I accomplish this?

Krumelur
  • 275
  • 1
  • 2
  • 9

5 Answers5

17

Use pgrep?

pgrep -U xxx yyy

it returns just the pid (or pids, if more than one process matches).

Marius Gedminas
  • 484
  • 3
  • 9
3

Use grep?

ps -u xxx | grep yyy | grep -v grep
RedGrittyBrick
  • 3,832
  • 1
  • 17
  • 23
2

You use comm to find PIDs common to both conditions:

ps -u xxx | sort > /tmp/ps-uxxx
ps -C yyy | sort > /tmp/ps-Cyyy
comm -1 -2 /tmp/ps-uxxx /tmp/ps-Cyyy

Using bash, you can use process substitution to avoid the need for temporary files:

comm -1 -2 <(ps -u xxx | sort) <(ps -C yyy | sort)
GargantuChet
  • 314
  • 1
  • 8
  • Works, thank you very much. ... But is there no easier way (without using pgrep, since this is not available in my context)? – guettli Feb 28 '17 at 08:31
  • What's not easy about this? – GargantuChet Mar 02 '17 at 06:21
  • 1
    I know what a `comm` does. But I use it only once a year. It's not intuitive for me. I guess everyone who uses it daily sees this different. The are good reasons why pgrep exists. Unfortunately pgrep is not available in my context .... But it's solved now. The root of the problem is (according to my point of view), that I need to support the very old operation system without pgrep. – guettli Mar 02 '17 at 07:59
0

A subtle refinement to the pgrep approach in the accepted answer (which I also upvoted).

When yyy happens to be a substring of another running command e.g. yyy is gnome-shell, we might get matches for gnome-shell-calendar-service as well. Point being, pgrep is good, but it doesn't completely answer the question (and is the reason I stopped using it).

By comparison, ps -C gnome-shell only returns matches for the gnome-shell process. I also hear @guettli's point about familiarity with commands. Your favorite sed or awk could be committed to muscle memory:

ps -fC gnome-shell | awk '($1=="the_user")'
ps -fC gnome-shell | sed -n '/^the_user\b/p'

If you just want the PID like pgrep, then awk can help:

ps -ouser=,pid= -C gnome-shell | awk '($1=="the_user"){print $2}'

You don't strictly need to replace -f with -o in the ps, but this post is about diminishing returns. If you need precise results, then this is your answer.

Rich
  • 135
  • 8
0

For the ones who need to achieve it on the fly (no script), here is a bit easier way.

ps -fp $(pgrep -d, -U theUser theCommand)
Sephi
  • 1