Get the process id from ps -ef grep (or Stop an application before removing it)

5,122

You can do

ps -U someUserName -o pid,comm | awk '/someProcessName/{print $1}'

(edited my answer and took the above line from my answer to your related question) or similar [1], or even better

pgrep -u myuser mybinaryname

to get the process id, or even simpler

pkill -u myuser mybinaryname

to directly kill the process.

Do some tests to determine the binary name and make sure it doesn't collide with other processes though.

(pgrep and pkill are most likely already installed on your system. Otherwise they are (on Debian based systems) in the package procps).


Note that a normal user most probably doesn't have privileges to kill other users' processes, so e.g. pkill mybinaryname need to be run with elevated privileges. It sounds like a script run by root (since it is uninstalling programs), so this might not be an issue.


[1]: awk picks first non-blank field by collapsing leading spaces which will appear if pid<10000 (on my system, since pidmax is 32767), which would confuse e.g. cut.

Share:
5,122

Related videos on Youtube

Jim
Author by

Jim

Updated on September 18, 2022

Comments

  • Jim
    Jim over 1 year

    I have an rpm and I want on uninstall to check if my application is running and if it is stop it before running the uninstall.
    My service runs under a specific user. How can I do this using bash in rpm spec?
    I.e. how can I know my service is running so that I can stop it?

    Update: If I do ps -ef|grep myUser how can I get the process id from the result so that I can do kill -9?

    • Daniel Andersson
      Daniel Andersson about 12 years
      Don't kill -9. Just kill. kill -9 is not nice, and not even helpful in most respects (might leave file descriptors hanging, create zombies, etc.). At least be sure you know exactly what kill -9 means before using it in a routine way.
  • Daniel Andersson
    Daniel Andersson about 12 years
    Do you have many users running the process, and only want to kill a the specific instance of a certain user? It sounds like you just want to kill the process, no matter who owns it. I will add to my answer that you might not (probably not) have privileges to kill other users' processes like this, so you might need to run it via sudo or similar.
  • Jim
    Jim about 12 years
    The process runs only under 1 specific user and there is 1 process running.The root will do this
  • Daniel Andersson
    Daniel Andersson about 12 years
    Then you don't need to explicitly restrict it a single user, but you can do it with pgrep -u myUser myBinaryName. I can add it to the answer.