文件写入锁和子进程
问题描述:
如果一个进程给一个文件一个写入锁,然后它产生一个子进程,是由子进程继承的锁吗?如果是,那么有2个进程有写锁,我知道有只有 1进程可以有写锁,有一些道理?这里是一个测试Python代码文件写入锁和子进程
#!/usr/bin/python
import fcntl
import time
import os
fp = open('test.ini','w')
fcntl.flock(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
pid = os.fork()
if pid > 0:
time.sleep(10)
exit(0)
if pid == 0:
time.sleep(100)
exit(0)
当父存在,我试图让文件test.ini的锁,但是失败,所以我想孩子有锁
答
文件锁与打开的文件描述符相关联。这意味着当你用dup()类似于系统调用(或者当子进程从父进程继承文件描述符时)复制你的描述符时,这些锁也被继承。 例如
flock(fd, LOCK_EX);//get a lock
newfd = dup(oldfd);//duplicating the file descriptors
flock(newfd, LOCK_UN);//THis call will release the lock using the duplicated file descriptor.
我希望这个信息有帮助。