0

Want to kill a process of a tree.
For example, in the A->B->C->D->E chain I want to kill process C,D,E but not A and B.

So i use setpgid(PID_C,0) to kill all the children of C and also C. It works fine for C++.

But the same thing I want to do with scripting.
Can anyone help me in this

jxh
  • 69,070
  • 8
  • 110
  • 193
  • http://stackoverflow.com/questions/6549663/how-to-set-process-group-of-a-shell-script –  Jul 07 '15 at 12:23

1 Answers1

0

I'm not really getting how are you sure that setpgid kills your process chain, normally setpgid function will join an existing process group or creates a new process group. (And its not C++)

Anyway following alternative script should work

Pass the process id of your chain's parent process, i.e. in your case its the pid of process B

Its recursively loops over the child processes of a given pid and signals each child process to be killed with 9 (SIGKILL) signal, from below-most order.

#!/bin/sh

function getcpid() {
    cpids=`pgrep -P $1|xargs`
    #echo "cpids=$cpids"
    for cpid in $cpids;
    do
        #echo "$cpid"
        getcpid $cpid
        kill -9 cpid
    done
}

getcpid $1
deimus
  • 9,565
  • 12
  • 63
  • 107
  • kill -9 pid is not working for me .. Suppose i give "kill -9 pid_C" then it should kill all the processes under C and also C , where as in my case its killing only C not its children. So i am using setpgid() to mark all the processes under C (including C) in a group and then killing that group. – Pragyan Paramita Das Jul 08 '15 at 11:23
  • The shell script I provided doesn't call `kill -9` on your topmost process only. Firstly it kills all the below-most children **recursively** then processes one level up until it reaches the process `C` and kills it. – deimus Jul 08 '15 at 13:35