2016-09-07 141 views
0

我通過啓動很多進程來啓動我的應用程序,我使用腳本(bash)啓動它。殺死進程並行啓動

  • 的filemane是:start.sh我用sudo ./start.sh運行
  • 腳本在start.sh是:

#!/bin/sh sudo p1 > p1.txt && p2 > p2.txt && p3 > p3.txt

停止我的應用我用ctrl-c但不是所有的進程停止。我知道我可以找到與ps aux | less | grep ...,這似乎很長,我想知道是否有和容易等待停止我的過程。

更新 遺憾就是這個,而不是(只有一個&

sudo f1/p1.py > logs/p1.txt & sudo f2/p2.sh > logs/p2.txt & sudo nodemon f3/p3.js > logs/p3.txt 
+2

如果你的'ps && P2 && P3 ...',那麼你只有一個進程運行時間。 p1成功完成後,p2開始,等等。 – anishsane

+0

另外,由於'start.sh'是以'sudo'開始的,所以你不需要用'sudo'明確地啓動'p1'。 – anishsane

+0

現在,這些單獨的過程如何反應到「ctrl + c」(或更準確地說,轉到SIGINT)取決於應用程序的編碼方式。它可以處理SIGINT,並根據編碼的方式成功或失敗。但按'ctrl + c'(傳遞SIGINT)並不意味着這個過程會結束。這是常見的/常見的行爲,但這並不是強制性的。 – anishsane

回答

1

商店的PID,並暗示或在退出時設置的陷阱殺死他們:

#!/bin/bash 
#  ^^^^ - NOT /bin/sh, as this code uses arrays 

pids=() 

# define cleanup function 
cleanup() { 
    for pid in "${pids[@]}"; do 
    kill -0 "$pid" && kill "$pid" # kill process only if it's still running 
    done 
} 

# and set that function to run before we exit, or specifically when we get a SIGTERM 
trap cleanup EXIT TERM 

sudo f1/p1.py > logs/p1.txt & pids+=("$!") 
sudo f2/p2.sh > logs/p2.txt & pids+=("$!") 
sudo nodemon f3/p3.js > logs/p3.txt & pids+=("$!") 

wait # sleep until all background processes have exited, or a trap fires 
0

如果你知道你在你的腳本開始的進程名,那麼你可以做這樣的事情,其全部殺死用這個名字進行處理。

例如:殺Skype的過程

pkill skype 

對於更詳細的選項看到man pkill

0

如果你知道你的shell的PID(進程ID),你可以這樣做:

pkill -TERM -P PPID 

其中PPID是你的shell的PID(子進程的父進程的PID)。

+0

'bash'中的'$$'通常不是shell'pid'嗎? –