Chinaunix首页 | 论坛 | 博客
  • 博客访问: 37741
  • 博文数量: 41
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 357
  • 用 户 组: 普通用户
  • 注册时间: 2014-04-20 16:26
文章分类

全部博文(41)

文章存档

2014年(41)

我的朋友

分类: LINUX

2014-05-04 20:51:40

互斥锁是为了解决生产者、消费者问题而产生的一种机制,主要用于进程间、线程间的同步。
记录锁:

记录锁通常用于进程中将文件锁住,保证文件操作的原子性,使用记录锁锁住文件,首先要定义一个struct flock变量,间这变量的值设置好,然后使用fcntl函数锁住文件,待操作完成在用fcntl函数解锁。
struct flock {
               ...
               short l_type;    /* Type of lock: F_RDLCK(设置共享读锁),
                                   F_WRLCK(设置独占写锁), F_UNLCK(解锁) */
               short l_whence;  /* How to interpret l_start:(开始锁位置参考点)
                                   SEEK_SET, SEEK_CUR, SEEK_END */
               off_t l_start;   /* Starting offset for lock (开始锁位置偏移量)*/
               off_t l_len;     /* Number of bytes to lock (锁文件的长度)*/
               pid_t l_pid;     /* PID of process blocking our lock
                                   (F_GETLK only) */
               ...
           };


  8 #include
  9 #include
 10 #include
 11 #include
 12 #include
 13 #include
 14
 15 void flock(int fd, short type, off_t sta, short whence, off_t len)
 16 {
 17     struct flock fl;
 18     fl.l_type = type;
 19     fl.l_start = sta;
 20     fl.l_whence = whence;
 21     fl.l_len = len;
 22
 23     fcntl(fd, F_SETLKW, &fl);
 24 }
 25
 26 int main(int argc, int argv)
 27 {
 28     int fd;
 29     fd = open("./aa", O_CREAT|O_WRONLY, 0777);
 30     if(fd < 0)
 31     {
 32         perror("open");
 33         exit(1);
 34     }
 35     fork();
 36     fork();
 37     fork();
 38     fork();
 39     fork();
 40     fork();
 41     while(1)
 42     {
 43         flock(fd, F_WRLCK, SEEK_SET, 0, 0);
 44         write(fd, "how ", 4);
 45         write(fd, "are ", 4);
 46         write(fd, "you ", 4);
 47         write(fd, "is ", 3);
 48         write(fd, "pig\n", 4);
 49         flock(fd, F_UNLCK, SEEK_SET, 0, 0);
 50     }
 51 }


阅读(193) | 评论(0) | 转发(0) |
0

上一篇:linux信号

下一篇:IO多路复用

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