0

我需要运行一个进程,等待几个小时,杀死它,然后重新启动它。有没有一种简单的方法可以使用 Python 或 Bash 完成此任务?我可以在后台运行它,但是如何识别它以使用 kill 呢?

4

7 回答 7

3

这是在 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)
于 2009-04-01T05:55:10.650 回答
3

使用 bash:

while true ; do
    run_proc &
    PID=$!
    sleep 3600
    kill $PID
    sleep 30
done

$!bash 变量扩展为最近启动的后台进程的 PID 。sleep只需等待一个小时,然后kill关闭该过程。

while循环只是一遍又一遍地做它。

于 2009-04-01T06:16:21.427 回答
2

在蟒蛇中:

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()是蟒蛇> = 2.6。

在 python <= 2.5 你可以使用它来代替:

os.kill(p.pid, signal.SIGTERM)
于 2009-04-01T10:12:16.803 回答
0

一个想法:将进程的 PID(由fork()您的子进程返回)保存到文件中,然后安排一个cron作业来终止它或手动终止它,从文件中读取 PID。

另一种选择:创建一个自动终止并重新启动进程的 shell 脚本包装器。与上面相同,但您可以将 PID 保存在内存中,根据需要休眠,终止进程,然后循环。

于 2009-04-01T05:52:05.993 回答
0

看看start-stop-daemon实用程序。

于 2009-04-01T05:52:52.167 回答
0

您总是可以编写一个脚本来搜索这些进程并在找到时杀死它们。然后添加一个cronjob来执行脚本。

查找具有已知名称的进程的进程 ID

杀死具有已知 ID 的进程

在 python中,os.kill()可用于杀死给定 id 的进程。

于 2009-04-01T05:53:16.583 回答
0

这不是一个理想的方法,但如果您知道程序的名称并且您知道它是系统上运行的唯一进程,您可以在 cron 中使用它:

0 */2 * * * kill `ps -ax | grep programName | grep -v grep | awk '{ print $1 }'` && ./scriptToStartProcess

这将在整点每两个小时运行一次并杀死 programName 然后再次启动该过程。

于 2009-04-03T13:26:36.877 回答