Search code examples
grepansiblepidps

How to get only the parent PID of a process and exclude child processes linked to it with grep


I am writing an ansible playbook that will go and kill PIDs.

I found a good answer that was relevant to me: https://stackoverflow.com/a/46541018/8863970

However, the first step which is Get running processes in my case I have two processes as follows:

# when i do: ps -ef | grep appp.py

ubuntu   17765     1  2 12:14 pts/0    00:00:04 python appp.py 
ubuntu   17784 17765  4 12:15 pts/0    00:00:05 /home/ubuntu/venvs/myvnv/bin/python /home/ubuntu/deploy/appp.py 
ubuntu   17844 14784  0 12:17 pts/0    00:00:00 grep --color=auto appp.py

It kills 17765 and then fails with:

failed: [10.10.1.1] (item=17784) => {"ansible_loop_var": "item", "changed": true, "cmd": "kill 17784", "delta": "0:00:00.002196", "end": "2020-04-26 12:23:22.833284", "item": "17784", "msg": "non-zero return code", "rc": 1, "start": "2020-04-26 12:23:22.831088", "stderr": "/bin/sh: 1: kill: No such process", "stderr_lines": ["/bin/sh: 1: kill: No such process"], "stdout": "", "stdout_lines": []}

Meaning... it can't find 17784 to kill.

Question is: How do I get only the parent PID (17784) with ps grep and then pass it on to kill it?


Solution

  • Tac this to the end | grep -v grep