首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

请问一个linux文件锁的有关问题

2012-04-03 
请教一个linux文件锁的问题#includestdio.h#includesys/stat.h#includesys/types.h#includefcntl.h

请教一个linux文件锁的问题
#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<unistd.h>
#include<errno.h>
#include<string.h>
my_error(char *p,int n){
  perror(p);
  printf("line=%d",n);
}

 int main()
{ int fd;
  char a[50]="abcdef"; 
  int n;
  char b[50];
  struct flock lock;
  fd=open("example.c",O_RDWR|O_CREAT,0666);
  if(fd==-1){
  my_error("open",__LINE__);
   
  // exit(1);
 }
  else
  printf("text is ok\n");
 
 if( write(fd,a,strlen(a)+1)==strlen(a)+1)
  my_error("write",__LINE__);
 
  printf("写入成功\n");  
n=lseek(fd,0,SEEK_END);
  if(n==-1)
  my_error("lseek",__LINE__);
 else
 printf("n=%d\n",n);
  n=lseek(fd,0,SEEK_SET);
 printf("n=%d\n",n);
read(fd,b,strlen(a)+1);
  printf("%s\n",b);
 memset(&lock,0,sizeof(struct flock ));
 lock.l_whence=SEEK_SET;
 lock.l_start=0;
 lock.l_len=0;
 lock.l_type=F_WRLCK;
 if( fcntl(fd,F_SETLK,&lock)==0)
  printf(" lock is ok\n");
 else 
  printf("error");
  if(fcntl(fd,F_GETLK,&lock)==0)
  printf("file %d is lock",getpid());
  if(lock.l_type==F_RDLCK)
  printf(" RDLCK");
  else if(lock.l_type==F_WRLCK)
  printf(" WRLCK");
  else if(lock.l_type==F_UNLCK)
  printf(" UNLCK");
   
getchar();
 close(fd);
 return 0;
}

想给文件加锁 为什么最后显示 UNLCK

[解决办法]
结构体lock的定义呢?。。。求源码
[解决办法]
貌似没有办法来获取文件上当前有哪些锁

F_GETLK 的准确语义是获取会阻止我的加锁操作的第一个锁
 If no lock is found that would prevent this lock from being created, the structure is left unchanged, except for lock type (l_type) which is set to F_UNLCK.



The definition of the F_GETLK command states that the information returned applies to an existing lock that would prevent us from creating our own lock. Since the F_SETLK and F_SETLKW commands always replace a process's existing lock if it exists, we can never block on our own lock; thus, the F_GETLK command will never report our own lock.

热点排行