文件锁,用于进程间同时对文件操作。
文件锁
#include<iostream> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <vector> #include <algorithm> #include <queue> using namespace std; #include<iostream> #include<cstring> #include<string> #include<iostream> #include<algorithm> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <stdio.h> int main() { FILE *fp= NULL; int fd; struct flock lock; memset(&lock,0,sizeof(lock)); lock.l_type=F_WRLCK; lock.l_whence=SEEK_SET; lock.l_start=0; lock.l_len=0; int n; while(cin>>n){ if(fp == NULL){ fp = fopen("a.txt", "w+"); fd = fileno(fp); } if(n == 1){ lock.l_type=F_UNLCK; if(fcntl(fd,F_SETLK,&lock)==0) { printf("unlock success.\n"); } else { printf("unlock fail.\n"); } }else if(n == 2){ int iRet = fcntl(fd,F_SETLKW,&lock); if(iRet==0) { printf("lock success.\n"); printf("decode succeeded.\n"); } } else if(n == 3){ cout << fwrite("hello world 1111111111 ", 1, 20, fp)<<endl; fclose(fp); fp = NULL; } } return 0; }
启动2个进程,然后操作命令码 2上锁 ,1解锁
可以看到进程1在锁住的情况下,进程2是 再上锁会被阻塞,直到进程1解锁,进程2才能获得锁。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步