挂起进程超时(卡住的操作系统调用)

2024-05-13 17:33:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python程序访问NFS挂载的文件系统。有时,文件系统变得不可访问并且操作系统统计(“/path/to/file”)将挂起进程。我尝试过下面的超时包装器片段,但在处理“坏”的操作系统调用时,它似乎并不有效(从某种意义上说,它不会返回):例如,它适用于:

with timeout(seconds=3)
   sleep(4)

但它不起作用:

^{pr2}$

有没有其他方法可以让我自己摆脱被绞死的过程?在

class timeout:
    """
    Usage:
        with timeout(seconds=3):
            sleep(4)
    """

    def __init__(self, seconds=1, error_message='Timeout'):
        self.seconds = seconds
        self.error_message = error_message

    def handle_timeout(self, signum, frame):
        raise TimeoutError(self.error_message)

    def __enter__(self):
        signal.signal(signal.SIGALRM, self.handle_timeout)
        signal.alarm(self.seconds)

    def __exit__(self, type, value, traceback):
        signal.alarm(0)

Tags: topathself程序messagesignaldefwith
2条回答

您可以使用看门狗进程

例如:

with timeout(seconds=3)
    watchdog_queue.put( (my_id,timeout=5) )
    os.stat("/nfs/mounted/filesystem")
    watchdog_queue.put( (my_id,clear) )

如果看门狗进程5秒内得到no(my_id,clear)消息,则使用my_id杀死进程/线程。在

你可以试试这个,它没有优化,但应该可以工作:

i=0
while i<200:
    try:
        os.stat("/nfs/mounted/filesystem")
        i=200
    except:
        time.sleep(1)

相关问题 更多 >