2014-09-01 40 views
0

如果一個進程給一個文件一個寫入鎖,然後它產生一個子進程,是由子進程繼承的鎖嗎?如果是,那麼有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的鎖,但是失敗,所以我想孩子有鎖

回答

0

文件鎖與打開的文件描述符相關聯。這意味着當你用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. 

我希望這個信息有幫助。