zoukankan      html  css  js  c++  java
  • 文件锁,用于进程间同时对文件操作。

    文件锁

    #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.
    "); 
                }
                else
                {
                    printf("unlock fail.
    ");
                }
            }else if(n == 2){
                int iRet = fcntl(fd,F_SETLKW,&lock);
                if(iRet==0)
                {
                    printf("lock success.
    ");
                    printf("decode succeeded.
    ");
                }
            }
            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才能获得锁。

  • 相关阅读:
    gluon模块进行数据加载-Dataset和DataLoader
    梯度相关概念
    plt.rcParams参数设置
    矩阵求导(二)
    矩阵求导(一)
    使用MXNet的NDArray来处理数据
    Win10环境下Anaconda安装常用指令以及环境管理
    Git使用vi或vim命令打开、关闭、保存文件
    工作中遇到的问题总结
    学习 Python3 语言
  • 原文地址:https://www.cnblogs.com/yuguangyuan/p/13374676.html
Copyright © 2011-2022 走看看