0

I have script as below

testscript.sh

#!/bin/bash

while true
do
  /sbin/tcpdump -n -c 2 -i eth0  >/tmp/pkt_eth0
  sleep 60
done

When I try to kill it testscript.sh vanish but tcpdump waiting process still there. Also for testscript.sh I am not able to use killall so need pid

$kill -15 pid

but would prefer

$killall -15 testscript.sh

to end script and all child processes. How it can be achieved?

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
coder007
  • 317
  • 1
  • 5
  • 12
  • If you ran the job in the background (append `&` to the command), and use the `wait` command to wait for completion, then you have much more control. For example you can `kill` using the job-number rather than the PID. You can trap signals (not SIGKILL) in the script using `trap`. – cdarke Oct 11 '18 at 08:35
  • I used trap to add clean_up script but waiting process still can not be killed somehow – coder007 Oct 11 '18 at 08:42

1 Answers1

2

If you set a minus sign before the process id, then the child processes are also killed. Test:

script.sh:

#!/bin/bash
while true
do
  ./script2.sh 
  sleep 60
done

script2.sh:

#!/bin/bash
for ((i=1;i<=10;i++))
do
    echo "$i"
    sleep 10
done

After running the command with ./script.sh, find the PID with ps aux | grep script (from a different terminal), and then kill it with:

kill -- -13859

Here 13859 is the PID of script.sh. After running ps aux | grep script you will see that both scripts have terminated.

Source: http://fibrevillage.com/sysadmin/237-ways-to-kill-parent-and-child-processes-in-one-command

user000001
  • 32,226
  • 12
  • 81
  • 108