2016年12月6日 星期二

[Linux 常見問題] Best way to kill all child processes

Source From Here
Question
want to kill a whole process tree. What is the best way to do this using any common scripting languages? I am looking for a simple solution.

How-To
You don't say if the tree you want to kill is a single process group. (This is often the case if the tree is the result of forking from a server start or a shell command line.) You can discover process groups using GNU ps as follows:
# ps x -o "%p %r %y %x %c "

If it is a process group you want to kill, just use the kill(1) command but instead of giving it a process number, give it the negation of the group number. For example to kill every process in group 5112, use kill -TERM -- -5112. Consider below demonstration shell script which help us to understand how it works more clear.
- test_sleep.sh
  1. #!/bin/sh  
  2. echo "Sleep 10 minutes"  
  3. sleep 600  
- test.sh
  1. #!/bin/sh  
  2.   
  3. echo "Sleep 1"  
  4. ./test_sleep.sh &  
  5. S1=$!  
  6. echo "Sleep 2"  
  7. ./test_sleep.sh &  
  8. S2=$!  
  9. wait $S1 $S2  
Let's execute test.sh:
# ./test.sh &
[1] 79863

# ps x -o "%p %r %y %x %c"
...
79863 79863 pts/2 00:00:00 test.sh
79864 79863 pts/2 00:00:00 test_sleep.sh
79865 79863 pts/2 00:00:00 test_sleep.sh
79866 79863 pts/2 00:00:00 sleep
79867 79863 pts/2 00:00:00 sleep
...

So we can try to list process tree:
# ps auxf

To kill test.sh and all its child process(s), do this way:
# kill -TERM -- -79863
[1]+ Terminated ./test.sh

// Make sure the test.sh and test_sleep.sh have been killed
# ps aux | grep test | grep -v grep


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...