日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

fcntl函数之文件锁 F_SETLKW

發布時間:2023/11/30 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 fcntl函数之文件锁 F_SETLKW 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

fcntl函數之文件鎖 F_SETLKW
F_SETLK與F_SETLKW的區別:
F_SETLK設的鎖遇到鎖被其他進程占用時,會立刻停止進程。
F_SETLKW上鎖是阻塞方式。設置的鎖因為其他鎖而被阻止設置時,該命令會等待相沖突的鎖被釋放。

#include <stdio.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <errno.h>/** * *./myfcntl content typestruct flock {...short l_type; F_RDLCK,F_WRLCK,F_UNLCKshort l_whence; How to interpret l_start: SEEK_SET, SEEK_CUR, SEEK_ENDoff_t l_start; Starting offset for lockoff_t l_len; Number of bytes to lockpid_t l_pid; PID of process blocking our lock (set by F_GETLK and F_OFD_GETLK)...};* */ int lock_reg(int fd, int cmd, short lock_type, short lock_whence, off_t lock_start, off_t lock_len) {struct flock lock;lock.l_type = lock_type;lock.l_whence = lock_whence;lock.l_start = lock_start;lock.l_len = lock_len;lock.l_pid = getpid();if (fcntl(fd, cmd, &lock) < 0) {if (errno == EACCES || errno == EAGAIN ) {printf("file lock by other processes.\n");return -1;}printf("lock file fail.\n");return -1;}if (lock_type == F_WRLCK) {printf("lock by %d.\n", getpid());} else if (lock_type == F_UNLCK) {printf("unlock by %d.\n", getpid());}return 0; }int reg_lock(int fd) {return lock_reg(fd, F_SETLK, F_WRLCK, 0, SEEK_SET, 0); } int reg_unlock(int fd) {return lock_reg(fd, F_SETLK, F_UNLCK, 0, SEEK_SET, 0); }int reg_lockw(int fd) {return lock_reg(fd, F_SETLKW, F_WRLCK, 0, SEEK_SET, 0); } int reg_unlockw(int fd) {return lock_reg(fd, F_SETLKW, F_UNLCK, 0, SEEK_SET, 0); }/* * *.myfcntl AAAAAA */ int main(int argv, char *argc[]) {char *buf;int i;int ret;int fd;if (argv < 2) {printf("argc error!\n");return -1;}fd = open("processes.txt", O_CREAT|O_RDWR|O_APPEND, 777);ret = reg_lockw(fd);if (ret !=0 ) {return -1;}sleep(5);buf = argc[1];i = 0;while (i < strlen(buf)) {if (write(fd, buf+i, sizeof(char)) < sizeof(char)) {printf("printf out error!\n");return -1;}printf(" %c:out by pid %d.\n", buf[i], getpid());i++;sleep(1);}ret = reg_unlockw(fd);if (ret !=0 ) {return -1;}close(fd);return 0; }

同時運行兩個進程,第二個被阻塞不退出,直到第一個進程解鎖,第二個進程再上鎖。
#結果
lock by 18687.
B:out by pid 18687.
B:out by pid 18687.
B:out by pid 18687.
B:out by pid 18687.
B:out by pid 18687.
B:out by pid 18687.
B:out by pid 18687.
unlock by 18687.
lock by 18686.
A:out by pid 18686.
A:out by pid 18686.
A:out by pid 18686.
A:out by pid 18686.
A:out by pid 18686.
A:out by pid 18686.
A:out by pid 18686.
unlock by 18686.
fcntl分為建議鎖和強制性鎖,默認是建議鎖模式,該模式下,一個文件被一個進程鎖住后,第二個進程是能直接往這個文件寫數據的。建議每次輸入數據前都有個上鎖操作。

總結

以上是生活随笔為你收集整理的fcntl函数之文件锁 F_SETLKW的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。