[英]How do I schedule a process' termination?
我需要運行一個進程,等待幾個小時,殺死它,然后重新啟動它。 有沒有一種簡單的方法可以用 Python 或 Bash 完成此任務? 我可以在后台運行它,但是如何識別它以使用 kill 呢?
這是在 Perl 中,但您應該能夠將其翻譯為 Python。
#!/usr/bin/perl
use strict;
use warnings;
#set times to 0 for infinite times
my ($times, $wait, $program, @args) = @ARGV;
$times = -1 unless $times;
while ($times--) {
$times = -1 if $times < 0; #catch -2 and turn it back into -1
die "could not fork" unless defined(my $pid = fork);
#replace child with the program we want to launch
unless ($pid) {
exec $program, @args;
}
#parent waits and kills the child if it isn't done yet
sleep $wait;
kill $pid;
waitpid $pid, 0; #clean up child
}
因為我想自學 Python,所以這里是 Python(我不相信這個代碼):
#!/usr/bin/python
import os
import sys
import time
times = int(sys.argv[1])
wait = int(sys.argv[2])
program = sys.argv[3]
args = []
if len(sys.argv) >= 4:
args = sys.argv[3:]
if times == 0:
times = -1
while times:
times = times - 1
if times < 0:
times = -1
pid = os.fork()
if not pid:
os.execvp(program, args)
time.sleep(wait)
os.kill(pid, 15)
os.waitpid(pid, 0)
使用 bash:
while true ; do
run_proc &
PID=$!
sleep 3600
kill $PID
sleep 30
done
$!
bash 變量擴展為最近啟動的后台進程的 PID。 sleep
只等待一個小時,然后kill
關閉該進程。
while
循環只是一遍又一遍地做它。
在 python 中:
import subprocess
import time
while True:
p = subprocess.Popen(['/path/to/program', 'param1', 'param2'])
time.sleep(2 * 60 * 60) # wait time in seconds - 2 hours
p.kill()
p.kill()
是 python >= 2.6。
在 python <= 2.5 你可以使用它來代替:
os.kill(p.pid, signal.SIGTERM)
一個想法:將進程的 PID(由子進程中的fork()
返回)保存到文件中,然后安排一個cron
作業來殺死它或手動殺死它,從文件中讀取 PID。
另一種選擇:創建自動終止並重新啟動進程的 shell 腳本包裝器。 同上,但是你可以保留memory中的PID,只要你需要就休眠,殺死進程,然后循環。
看看start-stop-daemon實用程序。
您總是可以編寫一個腳本來搜索這些進程並在找到時殺死它們。 然后添加一個cronjob來執行腳本。
在 python中,os.kill()可用於殺死給定 id 的進程。
這不是一個理想的方法,但如果您知道程序的名稱並且您知道它是系統上運行的唯一進程,您可以在 cron 中使用它:
0 */2 * * * kill `ps -ax | grep programName | grep -v grep | awk '{ print $1 }'` && ./scriptToStartProcess
這將在整點每兩個小時運行一次並殺死 programName 然后再次啟動該過程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.