Chinaunix首页 | 论坛 | 博客
  • 博客访问: 723968
  • 博文数量: 77
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1173
  • 用 户 组: 普通用户
  • 注册时间: 2014-05-16 11:20
个人简介

将技术做到极致...

文章分类

全部博文(77)

文章存档

2019年(3)

2015年(27)

2014年(47)

分类: LINUX

2014-05-16 11:42:02

    最近在工作中遇到一个问题?在使用libconfig开源库读写配置文件时,发现会读写冲突,后来在libconfig库的源代码添加调试信息,发现开源的libconfig源代码config_read_file()、config_write_file()这两个函数是没有对读写配置文件添加锁导致的。
    发现问题的原因之后,我就尝试修改源代码,添加对读写配置文件添加锁,具体添加代码如下:
    未添加锁int config_read_file(config_t *config, const char *filename){
     int ret;
      FILE *stream = fopen(filename, "rt");
      if(! stream)
      {
        config->error_text = __io_error;
        config->error_type = CONFIG_ERR_FILE_IO;
        return(CONFIG_FALSE);
      }
      ret = __config_read(config, stream, filename, NULL);
      fclose(stream);
      return(ret);     
}
    已添加锁的int config_read_file(config_t *config, const char *filename)
{
  int ret;
  FILE *stream ;
  int fd = open(filename,O_RDONLY);
  struct flock lock;
  
  if(fd < 0)
  {
 config->error_text = __io_error;
 config->error_type = CONFIG_ERR_FILE_IO;
 return(CONFIG_FALSE);
  }


  lock.l_whence = SEEK_SET;
  lock.l_start = 0;
  lock.l_len = 0;
  lock.l_type   =  F_RDLCK;
lock:
  if ((fcntl(fd, F_SETLKW,&lock))==-1) {
      if (errno == EINTR)
 {
         goto lock;
 }
 else
 {
 config->error_text = __io_error;
 config->error_type = CONFIG_ERR_FILE_IO;
 fprintf(stderr,"%s,%d: set readlock err!\n",__FUNCTION__,__LINE__);
 return(CONFIG_FALSE);
 }
  }
  stream = fopen(filename, "rt");
  if(! stream)
  {
close(fd);
    config->error_text = __io_error;
    config->error_type = CONFIG_ERR_FILE_IO;
    return(CONFIG_FALSE);
  }
  ret = __config_read(config, stream, filename, NULL);
  fclose(stream);
  
  lock.l_whence = SEEK_SET;
  lock.l_start = 0;
  lock.l_len = 0;
  lock.l_type   =   F_UNLCK;
unlock:
  if ((fcntl(fd, F_SETLKW,&lock))==-1) {
      if (errno == EINTR) {
          goto unlock;
 }
  }
  close(fd);
  return(ret);
}

config_write_file()添加锁参考config_read_file()添加。


    第一次写工作日志,第一次写博客,写的不好的地方,请大家多多鼓励,我决定坚持把工作中遇到问题,以博客的方式记录下来,一方面对自己工作遇到问题的总结,另一方面
希望对大家遇到同样问题时,提供参考帮助。。。。。
阅读(1088) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:glib编译报错处理

给主人留下些什么吧!~~