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\n",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\n",
lock.l_pid);
//getchar();
}
}
}

file_lock(testfd,F_WRLCK);//加锁

//需要保护的操作

file_lock(testfd,F_UNLCK);//解锁

最新文章

  1. PLSQL配置新的oracle实例
  2. logstash插件
  3. 自己存档:ajax 动态提交form
  4. BZOJ1880: [Sdoi2009]Elaxia的路线
  5. Python::OS 模块 -- 简介
  6. eclipse中project-&gt;clean的作用是什么
  7. 《科学》封面:人工智能终于能像人类一样学习 zz
  8. 500 TypeError: Cannot read property &#39;connect.sid&#39; of undefined
  9. 在Linux命令行窗口中,怎么向上翻页?
  10. part 5 Two way databinding in AngularJS
  11. 【原】Storm 守护线程容错机制
  12. FLASH ROM与EEPROM的区别
  13. 【Android工具类】Activity管理工具类AppManager
  14. Lock(二)解决Lock问题
  15. Eclipse用法:自动生成get和set方法
  16. 校园网IPv6加速
  17. C#语言中的XmlSerializer类的XmlSerializer.Deserialize (Stream)方法举例详解
  18. 利用百度编辑器和IIS限制文件上传的大小
  19. C之attribute用法
  20. Linux top、VIRT、RES、SHR、SWAP(S)、DATA Memory Parameters Detailed

热门文章

  1. 剑指offer_面试题_从上往下打印二叉树
  2. 黑马day15 文件上传&amp;amp;apche的工具包
  3. Objective-C —内存管理(上)
  4. java日期类型与字符串类型的相互转换
  5. JSP学习(一)
  6. 【参考】IBM sun.io.MalformedInputException and text encoding conversions transforms numerals to their word equivalents - United States
  7. C++调用约定和名字约定 thiscall
  8. 列表的初识,列表的索引切片,列表的增删改查,列表的嵌套,元组的初识,range
  9. luogu P4139 上帝与集合的正确用法(扩展欧拉定理)
  10. luogu P3765 总统选举(线段树维护摩尔投票+平衡树)