linux api

flockfile


 void flockfile(FILE *filehandle);


進程內線程的互斥, 針對文件指針,同一文件的不同的文件指針對應不同的鎖,不會互相影響
fp1 = fopen("xx", "w+");
fp2 = fopen("xx", "w+");
// 下面倆個均可鎖上
flockfile(fp1); 
flockfile(fp2);

fcntl


fcntl(fd, F_SETLK, &lock);

進程間互斥鎖,針對的是具體的文件對象,可以對文件內某個具體區域上鎖,同一進程內,不論文件描述符(通過open,dup等獲得新的fd)是否相同,只要它們指的是同一文件,便是指的同一個鎖
fd1 = open("xx", ...); 
fcntl(fd1,F_SETLK, ...);  // 
fd2 = open("xx", ...);
// 同一進程內的後來的鎖總是會生效
fcntl(fd1, F_SETLK, ...);  // 生效
fcntl(fd1, F_SETLK, ...);  // 生效
fcntl(fd2, F_UNLK, ...); // fd1上的鎖也被釋放


flock

int flock(int fd, int operation);

進程間互斥鎖,針對的是文件描述符;同一文件不同文件描述符對應相同的鎖,鎖住整個文件
同一進程內,被鎖住後,後面再鎖會失敗
flock不提供鎖檢查,也就是說在用flock之前需要用戶自己去檢查一下是否已經上了鎖,說明白點就是讀寫文件之前用一下flock檢查一下文件有沒有上鎖
A  call  to  flock() may block if an incompatible lock is held by another process
 Locks created by flock() are associated with an open file table entry.  This means that duplicate file  descriptors  (cre?
       ated  by,  for  example, fork(2) or dup(2)) refer to the same lock, and this lock may be modified or released using any of
       these descriptors.  Furthermore, the lock is released either by an explicit LOCK_UN operation on any  of  these  duplicate
       descriptors, or when all such descriptors have been closed.




       If a process uses open(2) (or similar) to obtain more than one descriptor for the same file, these descriptors are treated
       independently by flock().  An attempt to lock the file using one of these file descriptors may be denied by  a  lock  that
       the calling process has already placed via another descriptor.


發佈了63 篇原創文章 · 獲贊 11 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章