- 论坛徽章:
- 0
|
- #include<stdio.h>
- #include<unistd.h>
- #include<fcntl.h>
- #include<errno.h>
-
- int getlock(struct flock* plock, int type, int whence);
-
-
- int main(int argc, char* argv[])
- {
- int fd = -1;
- if((fd = open("/home/cyc/proc/a.bat", O_RDONLY)) < 0)
- {
- perror("open file failed!!\n");
- return 0;
- }
-
- struct flock lock1;
- struct flock lock2;
- struct flock lock3;
- getlock(&lock1, F_RDLCK, SEEK_SET);
- if(fcntl(fd, F_SETLK, &lock1) < 0)
- {
- perror("set lock failed!!\n");
- return 0;
- }
- else
- {
- fprintf(stdout, "set lock success!!\n");
- }
-
- fprintf(stdout, "get lock info\n");
- getlock(&lock2, F_RDLCK, SEEK_SET);
- if(fcntl(fd, F_GETLK, &lock2) < 0)
- {
- fprintf(stderr, "set lock failed!!");
- return 0;
- }
- if(lock2.l_type == F_UNLCK)
- {
- fprintf(stdout, "no lock!!\n");
- }
- else if(lock2.l_type == F_RDLCK)
- {
- fprintf(stdout, "have read lock!!\n");
- }
- else if(lock2.l_type == F_WRLCK)
- {
- fprintf(stdout, "have write lock!!\n");
- }
-
- getlock(&lock3, F_UNLCK, SEEK_SET);
- if(fcntl(fd, F_SETLK, &lock3) < 0)
- {
- perror("set lock failed!!\n");
- return 0;
- }
-
- return 0;
- }
-
- int getlock(struct flock* plock, int type, int whence)
- {
- if(plock == NULL)
- {
- perror("flock pointer is NULL\n");
- return -1;
- }
-
- plock->l_type = type;
- plock->l_whence = whence;
- plock->l_start = 0;
- plock->l_len = 0;
- plock->l_pid = getpid();
-
- return 0;
- }
复制代码 在加共享锁成功后,我再读取fd对应的锁信息,结果是:
读不到,说没有锁信息:
- set lock success!!
- get lock info
- no lock!!
-
复制代码 加了锁不是可以获取的到么,为什么获取不到呢。在线等待。 |
|