利用文件锁控制程序的执行

     我们在写程序的时候,需要同步控制的时候往往利用线程锁对程序进行加锁控制,哈哈,昨天看《UNIX网络编程》,里面提到对程序可以利用文件锁进行程序控制,觉得挺有意思,就拿过来试试。

      首先,我们需要知道一个库函数和一个结构体:fcntl,struct flock,没错,函数的意思就是文件控制,结构体的意思是文件锁结构。由于,之前看到过这两个东西,网上的介绍也很多,在这里就不多做介绍了,不懂的同学百度或者谷歌一下吧,在这里,提供一段测试程序,加锁,解锁的思想来自《Unix 网络编程》

 

  1. /*利用文件给程序加锁*/  
  2.   
  3. #include <unistd.h>  
  4. #include <sys/file.h>  
  5. #include <sys/types.h>  
  6. #include <sys/stat.h>  
  7. #include <stdio.h>  
  8. #include <stdlib.h>  
  9. #include <errno.h>  
  10. #include <string.h>  
  11.   
  12. static struct flock lock_it, unlock_it;  
  13.   
  14. static int lock_fd = -1;  
  15.   
  16. void dlut_lock_init(char *);  
  17. void dlut_lock_wait();  
  18. void dlut_lock_release();  
  19.   
  20. int main(int argc, char **argv, char **environ)  
  21. {  
  22.     dlut_lock_init("test.XXXXXX");  
  23.   
  24.     dlut_lock_wait();  
  25.   
  26.     if (!fork())  
  27.     {  
  28.         dlut_lock_wait();  
  29.   
  30.         printf("hello, this is child %d\n", getpid());  
  31.   
  32.         sleep(3);  
  33.   
  34.         dlut_lock_release();  
  35.   
  36.         exit(0);  
  37.     }  
  38.   
  39.     printf("hello, this is parent %d\n", getpid());  
  40.   
  41.     dlut_lock_release();  
  42.   
  43.     sleep(1);  
  44.   
  45.     return 0;  
  46. }  
  47.   
  48. void dlut_lock_init(char *path_name)  
  49. {  
  50.     char lock_file[1024];  
  51.   
  52.     char file_name[1024];  
  53.   
  54.     strcpy(lock_file, path_name);  
  55.   
  56.     strcpy(file_name, mktemp(lock_file));  
  57.   
  58.     lock_fd = open(file_name, O_RDWR | O_CREAT, 0666);  
  59.   
  60.     unlink(lock_file);  
  61.   
  62.     lock_it.l_type = F_WRLCK;  
  63.     lock_it.l_whence = SEEK_SET;  
  64.     lock_it.l_start = 0;  
  65.     lock_it.l_len = 0;  
  66.   
  67.     unlock_it.l_type = F_UNLCK;  
  68.     unlock_it.l_whence = SEEK_SET;  
  69.     unlock_it.l_start = 0;  
  70.     unlock_it.l_len = 0;  
  71. }  
  72.   
  73. void dlut_lock_wait()  
  74. {  
  75.     int rc;  
  76.   
  77.     while ((rc = fcntl(lock_fd, F_SETLKW, &lock_it)) < 0)  
  78.     {  
  79.         if (errno == EINTR)  
  80.             continue;  
  81.         else  
  82.         {  
  83.             perror("fcntl error...");  
  84.   
  85.             exit(1);  
  86.         }  
  87.     }  
  88.   
  89.     return;  
  90. }  
  91.   
  92. void dlut_lock_release()  
  93. {  
  94.     if (fcntl(lock_fd, F_SETLKW, &unlock_it))  
  95.     {  
  96.         perror("fcntl error");  
  97.   
  98.         exit(2);  
  99.     }  
  100.   
  101.     return;  
  102. }  


      我的意思是,父进程首先获取文件锁,之后打印一行字,接着子进程才能打印一行字。

posted @ 2014-01-08 16:26  刘俊鹏123  阅读(349)  评论(0编辑  收藏  举报
重生之大文豪