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

 

 

文件锁

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

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

 

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

 

原文链接: https://www.cnblogs.com/yuguangyuan/p/13374676.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/397618

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月11日 上午9:39
下一篇 2023年4月11日 上午9:40

相关推荐