在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()
fileno()
方法返回运行库分配的文件号。给定文件号后,您可以调用msvcrt.get_osfhandle()
来获取Win32文件句柄。在调用SetHandleInformation
时使用此句柄。因此,下面的方法可能会起作用:我不确定
win32api
模块的确切用法,但这应该有助于弥合Python文件对象和Win32句柄之间的差距。在我不知道多处理模块,但是使用subprocess模块,您可以指示它不要继承任何文件描述符:
或者,可以使用os.closerange关闭子进程中的所有文件描述符
打开文件句柄后,可以使用SetHandleInformation()函数删除
HANDLE_FLAG_INHERIT
标志。在相关问题 更多 >
编程相关推荐