文件锁,用于进程间同时对文件操作。

文件锁

#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才能获得锁。

猜你喜欢

转载自www.cnblogs.com/yuguangyuan/p/13374676.html