flock()會依參數operation所指定的方式對參數fd所指的文件作各類鎖定或解除鎖定的動做。此函數只能鎖定整個文件,沒法鎖定文件的某一區域。 函數
返回值 返回0表示成功,如有錯誤則返回-1,錯誤代碼存於errno。 測試
test1.c: this
#include <sys/file.h> #include <stdio.h> #include <stdlib.h> int main() { FILE *f = fopen("temp", "w+"); if(!f) { printf("error file\n"); return 0; } if(0 == flock(fileno(f), LOCK_EX)) { printf("lock...\n"); getchar(); fclose(f); flock(fileno(f), LOCK_UN); } else { printf("lock failed\n"); } return 0; }
test2.c spa
#include <sys/stat.h> #include <sys/types.h> #include <sys/file.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include <fcntl.h> int main() { FILE *fp; char text[]="this is a test!"; if((fp = fopen("temp", "w+")) == 0) printf("can't open file!\n"); else { printf("open file success!\n"); int i = flock(fileno(fp), LOCK_SH | LOCK_NB); // 加鎖以判斷文件是否已經被加鎖了 printf("%d\n", i); flock(fileno(fp), LOCK_UN); fwrite(text, strlen(text), 1, fp); } fclose(fp); return 0; }測試以下:
在終端1中,運行test1 code
在終端2中,運行test2 繼承
這裏主要說明的是在test2.c中,對文件的操做也是要利用加鎖來判斷文件是否已經被加鎖了, 進程
int i = flock(fileno(fp), LOCK_SH | LOCK_NB);上面這行代碼就是實現這個功能, 注意第二個參數,若是沒有LOCK_NB的話,若文件已加鎖則會進程阻塞,而上面的方式則不會出現這種問題;另外第一個參數,切勿直接傳入(int)fp
i == 0 表示文件加鎖成功, i == -1 表示文件已被加鎖,不建議執行後續操做 get
flock函數的加鎖是須要配合使用的,在文件操做以前,首先利用加鎖成功與否來斷定文件是否被加鎖,若成功再進行後續的代碼;不然表示文件被鎖 string