利用文件锁控制程序的执行
我们在写程序的时候,需要同步控制的时候往往利用线程锁对程序进行加锁控制,哈哈,昨天看《UNIX网络编程》,里面提到对程序可以利用文件锁进行程序控制,觉得挺有意思,就拿过来试试。
首先,我们需要知道一个库函数和一个结构体:fcntl,struct flock,没错,函数的意思就是文件控制,结构体的意思是文件锁结构。由于,之前看到过这两个东西,网上的介绍也很多,在这里就不多做介绍了,不懂的同学百度或者谷歌一下吧,在这里,提供一段测试程序,加锁,解锁的思想来自《Unix 网络编程》
- /*利用文件给程序加锁*/
- #include <unistd.h>
- #include <sys/file.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <errno.h>
- #include <string.h>
- static struct flock lock_it, unlock_it;
- static int lock_fd = -1;
- void dlut_lock_init(char *);
- void dlut_lock_wait();
- void dlut_lock_release();
- int main(int argc, char **argv, char **environ)
- {
- dlut_lock_init("test.XXXXXX");
- dlut_lock_wait();
- if (!fork())
- {
- dlut_lock_wait();
- printf("hello, this is child %d\n", getpid());
- sleep(3);
- dlut_lock_release();
- exit(0);
- }
- printf("hello, this is parent %d\n", getpid());
- dlut_lock_release();
- sleep(1);
- return 0;
- }
- void dlut_lock_init(char *path_name)
- {
- char lock_file[1024];
- char file_name[1024];
- strcpy(lock_file, path_name);
- strcpy(file_name, mktemp(lock_file));
- lock_fd = open(file_name, O_RDWR | O_CREAT, 0666);
- unlink(lock_file);
- lock_it.l_type = F_WRLCK;
- lock_it.l_whence = SEEK_SET;
- lock_it.l_start = 0;
- lock_it.l_len = 0;
- unlock_it.l_type = F_UNLCK;
- unlock_it.l_whence = SEEK_SET;
- unlock_it.l_start = 0;
- unlock_it.l_len = 0;
- }
- void dlut_lock_wait()
- {
- int rc;
- while ((rc = fcntl(lock_fd, F_SETLKW, &lock_it)) < 0)
- {
- if (errno == EINTR)
- continue;
- else
- {
- perror("fcntl error...");
- exit(1);
- }
- }
- return;
- }
- void dlut_lock_release()
- {
- if (fcntl(lock_fd, F_SETLKW, &unlock_it))
- {
- perror("fcntl error");
- exit(2);
- }
- return;
- }
我的意思是,父进程首先获取文件锁,之后打印一行字,接着子进程才能打印一行字。