是的,不同的进程可以同时在同一个目录中创建不同的文件。每个进程都有自己独立的文件描述符表,因此它们可以同时对同一个目录进行写入操作。
以下是一个示例代码,展示了两个进程同时在同一个目录中创建不同的文件:
import os
def create_file(process_id):
# 获取当前进程的进程ID
pid = os.getpid()
# 构造文件名
filename = f"file_{pid}_{process_id}.txt"
# 创建文件
with open(filename, 'w') as f:
f.write(f"This is file {process_id} created by process {pid}")
print(f"Process {pid} created file {filename}")
if __name__ == '__main__':
# 创建两个子进程
pid1 = os.fork()
pid2 = os.fork()
if pid1 > 0 and pid2 > 0:
# 等待子进程退出
os.waitpid(pid1, 0)
os.waitpid(pid2, 0)
elif pid1 == 0 and pid2 > 0:
# 第一个子进程
create_file(1)
elif pid1 > 0 and pid2 == 0:
# 第二个子进程
create_file(2)
运行此代码将创建两个子进程,每个子进程都会在同一个目录中创建一个不同的文件。文件名由进程ID和进程特定的ID(1或2)构成。
下一篇:不同的精灵之间碰撞不起作用?