Reputation: 8278
I have a script that runs from a newly created shell. OS is Red Hat Enterprise Linux Server release 5.4 (Tikanga). In certain point when the script detects that some application (started by the script) is hanging the script tries to terminate all the procesess it started. I assumed that the correct command for terminating all processes started by current user in current shell is:
pkill /?
The problem is that it kills sshd that is started in parent shell (by init.d) and the putty console disconnects showing error message.
I wonder:
I have found some solution where i store all the PIDs and when the script needs to terminate them I run in the loop the following:
[ws@RHDev ~]# pkill $(ps aux | grep $pid | awk '{print $2}')
However, I am looking for one-liner that simply terminates all the processes started by the current script.
Upvotes: 0
Views: 2724
Reputation: 136256
I assumed that the correct command for terminating all processes started by current user in current shell is:
pkill /?
This command matches every single process in the system because it effectively requires only 0 symbols from process name to match. pgrep -l /?
demonstrates that.
How is it possible for specific user in specific shell to terminate process started by other user in parent shell?
From man kill(2)
:
For a process to have permission to send a signal it must either be
privileged (under Linux: have the CAP_KILL capability), or the real or
effective user ID of the sending process must equal the real or saved
set-user-ID of the target process. In the case of SIGCONT it suffices
when the sending and receiving processes belong to the same session.
Do you invoke pkill
from user root
?
What would be correct command to terminate all processes started by the script currently running?
When bash
starts it creates its own process group. Child processes it creates are put in the same process group. Hence:
kill -- -$$
Kills all processes started by the current script. Provided that those processes didn't become group leaders.
Upvotes: 1
Reputation: 1882
You can filter subprocesses by the current process pid. The ps command can do this using the --ppid parameter.
ps opid --ppid=7051 | tail -n +2 | xargs kill
here tail -n +2 is
to strip the ps
headers.
Upvotes: 1