Skip to main content
 首页 » 编程设计

python 2.7之运行子进程并在用户时间超过最大时间时终止它

2024年11月01日10Free-Thinker

我正在编写 Python 2.7,它需要运行子进程并在子进程用户时间 超过最大时间时终止它。
用户时间的定义可以在this answer中找到至 What do 'real', 'user' and 'sys' mean in the output of time(1)?
到目前为止我有这个:

代码

from multiprocessing import Process 
import time 
 
def do_something(): 
    pass 
 
def run_process_limited_time(max_seconds): 
 
    # init Process 
    p = Process(target=do_something, args=()) 
 
    # start process 
    p.start() 
 
    run_time = 0; 
    sleep_time = 1; 
 
    while 1: 
 
        # sleep for sleep_time seconds 
        time.sleep(sleep_time) 
 
        # increase run time 
        run_time += sleep_time 
 
        # if process is not alive, we can break the loop 
        if not p.is_alive(): 
            break 
 
        # if process is still alive after max_seconds, kill it! 
        # TBD - condition is not sufficient  
        elif run_time > max_seconds: 
            p.terminate() 
            break 
 
def main(): 
    run_process_limited_time(10) 
 
if __name__ == "__main__": 
    main() 

问题

条件 elif run_time > max_seconds 不够好。我想检查最大秒数是否不超过仅限用户时间。不确定我是否可以使用 Process 模块来完成,但我乐于接受新想法。

请您参考如下方法:

使用 resource 的替代方案模块。可以使用 signal module 来处理超时.可以通过多种方式处理返回结果,其中一些在多处理 documentation 中有所描述。 .

from multiprocessing import Process 
import time 
import resource 
import signal 
 
def do_something(): 
    import resource 
    resource.setrlimit(resource.RLIMIT_CPU, (1,1)) 
    def f(signo, stackframe): 
        raise Exception('stop') 
    signal.signal(signal.SIGXCPU, f) 
    try: 
        while 1: 
            print 'hello' 
    except: 
        print 'aborted' 
 
def run_process_limited_time(function): 
 
    # init Process 
    p = Process(target=function, args=()) 
 
    # start process 
    p.start() 
 
    p.join(2) 
    p.terminate() 
 
 
if __name__ == "__main__": 
    run_process_limited_time(do_something)