Getting PID by process name and user?

Could I get the PID dependent on process AND user (say, process x belonging to user y -- in case there are two processes with the same name)?

And could I then let the PID be written to a variable on which I could execute another command (say "kill variable")?

Many questions, I know, but I had no clue to what "working with Tiger" can really mean (I am a switcher from Windows).

Posted on Sep 17, 2005 8:43 AM

Reply
11 replies

Sep 17, 2005 10:28 AM in response to Jochen Kaiserswerth

Hi Jochen,
If you didn't change "aUser" in anaxamander's command into the user on your machine that is running TextEdit, there won't be a match. However, even if you do, anaxamander's command won't find TextEdit because the command is too long for the standard terminal window. (80 characters wide) One could use the "-w" option to ps to prevent it from truncating the string. However, the longer the command, the greater the opportunity there is for a false match.

Besides that, if you're going to use awk, which I would, one might as well use that for the matching. With all of those considerations, I would use the following to get the process ID you want to kill:

ps -axo pid,user,ucomm | awk '{ if ( $2 == "<UserName>" && $3 == "TextEdit" ){ print $1 }}'

In my example, you would replace <UserName> with you own username.

As should be evident, there are many ways to do this in UNIX. The optimal way would depend on what you wanted to match.
--
Gary
~~~~
Be frank and explicit with your lawyer ... it is his business
to confuse the issue afterwards.

Sep 17, 2005 11:58 AM in response to Jochen Kaiserswerth

Hi Jochen,
Anaxamander was right on in his use of "kill". To do it with a variable as you suggest, use anaxamander's first method:

PID=`ps -axo pid,user,ucomm | awk '{ if ( $2 == "<UserName>" && $3 == "TextEdit" ){ print $1 }}'`
kill $PID

or you could do it directly as anaxamander did the second time:

kill `ps -axo pid,user,ucomm | awk '{ if ( $2 == "<UserName>" && $3 == "TextEdit" ){ print $1 }}'`

--
Gary
~~~~
The cost of feathers has risen, even down is up!

Sep 17, 2005 12:03 PM in response to Jochen Kaiserswerth

Jochen,
As anaxamander noted you can turn the result of a command into a varaible" by enclosing it in the tics above the tab key:``

set killvariable = `ps -axo pid,user,ucomm | awk '{ if ( $2 == "<UserName>" && $3 == "TextEdit" ){ print $1 }}' `
echo $killvariable

(note the tics above the tab key are not single quote marks, which would be the tics next to the enter key)

Reese

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

Getting PID by process name and user?

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.