"防止多进程库中的文件句柄继承"

2024-10-04 09:17:44 发布

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

在windows上使用多处理时,任何打开的文件句柄都会被派生的进程继承。这有一个令人不快的副作用锁定他们。在

我对其中一个感兴趣:
1) 防止继承
2) 从派生进程释放文件的方法

考虑下面的代码,它在OSX上运行良好,但在windows上崩溃操作系统重命名在

from multiprocessing import Process
import os

kFileA = "a.txt"
kFileB = "b.txt"

def emptyProcess():
    while 1:
        pass

def main():
    # Open a file and write a message
    testFile = open(kFileA, 'a')
    testFile.write("Message One\n")

    # Spawn a process
    p = Process(target=emptyProcess)
    p.start()

    # Close the file
    testFile.close()

    # This will crash
    # WindowsError: [Error 32] The process cannot access the file
    #               because it is being used by another process
    os.rename(kFileA, kFileB)

    testFile = open(kFileA, 'a')
    testFile.write("Message Two\n")
    testFile.close()

    p.terminate()


if __name__ == "__main__":
    main()

Tags: 文件importtxt进程osmainwindowsdef
3条回答

fileno()方法返回运行库分配的文件号。给定文件号后,您可以调用msvcrt.get_osfhandle()来获取Win32文件句柄。在调用SetHandleInformation时使用此句柄。因此,下面的方法可能会起作用:

win32api.SetHandleInformation(
    msvcrt.get_osfhandle(testFile.fileno()),
    win32api.HANDLE_FLAG_INHERIT,
    0)

我不确定win32api模块的确切用法,但这应该有助于弥合Python文件对象和Win32句柄之间的差距。在

我不知道多处理模块,但是使用subprocess模块,您可以指示它不要继承任何文件描述符:

If close_fds is true, all file descriptors except 0, 1 and 2 will be closed before the child process is executed. (Unix only). Or, on Windows, if close_fds is true then no handles will be inherited by the child process. Note that on Windows, you cannot set close_fds to true and also redirect the standard handles by setting stdin, stdout or stderr.

或者,可以使用os.closerange关闭子进程中的所有文件描述符

Close all file descriptors from fd_low (inclusive) to fd_high (exclusive), ignoring errors. Availability: Unix, Windows.

打开文件句柄后,可以使用SetHandleInformation()函数删除HANDLE_FLAG_INHERIT标志。在

相关问题 更多 >