zoukankan      html  css  js  c++  java
  • 用fcntl锁一个文件来保护操作

    int testfd; /* fd for test*/

    if((testfd = open("/usr/local/pgsql/bin/test_fd",O_RDWR|O_CREAT,0666)<0))
    {
    perror("open test_fd is error!");
    exit(1);
    }

    /* add fcntl lock function file_lock(int fd,int type) */
    void file_lock (int fd,int type)
    {
    struct flock lock;
    lock.l_type = type;
    lock.l_whence = SEEK_SET;
    lock.l_start = 0;
    lock.l_len = 0;

    while(1)
    {
    if ((fcntl(fd,F_SETLK,&lock)==0))
    {
    if (lock.l_type == F_RDLCK)
    printf("you got a readlock,the pid = %d",getpid());
    if (lock.l_type == F_WRLCK)
    printf("you got a writelock,the pid =%d",getpid());
    if (lock.l_type == F_UNLCK)
    printf("you got a realeselock,the pid = %d",getpid());
    return ;/* add lock success and return */
    }
    /* add lock fail */
    fcntl(fd,F_GETLK,&lock); /* get file lock info ,give it to lock */
    if (lock.l_type!=F_UNLCK) /* reason of can't add lock */
    {
    if (lock.l_type == F_RDLCK) /* there is a read lock */
    printf("it is already a lock!thd pid =%d ",lock.l_pid);
    else if (lock.l_type ==F_WRLCK) /* there is a write lock */
    printf("it is already a write lock!the pid =%d ",
    lock.l_pid);
    //getchar();
    }
    }
    }

    file_lock(testfd,F_WRLCK);//加锁

    //需要保护的操作

    file_lock(testfd,F_UNLCK);//解锁

  • 相关阅读:
    Struts2 xml表单验证
    struts2表单验证-整合国际化
    Strut2-Ajax总结
    java中的线性安全和不安全
    智游推送试用
    推送的重连策略
    Android本地通知的实现方式
    MyBatis框架学习二
    Java基础学习 2 (选择结构,循环结构)
    Java基础学习 1 (变量,数据类型,运算符)
  • 原文地址:https://www.cnblogs.com/songyuejie/p/3979322.html
Copyright © 2011-2022 走看看