+ -
当前位置:首页 → 问答吧 → 文件上锁问题

文件上锁问题

时间:2010-07-29

来源:互联网

# include <stdio.h>
# include <unistd.h>
# include <string.h>
# include <fcntl.h>
# include <errno.h>

static void
Lock(void)
{
  int fd=0;
  do{
        fd=open("file.lck",O_WRONLY|O_CREAT|O_EXCL,0666);
        if(fd==-1)
         {
              if(errno==EEXIST){
                 sleep(1);
         }else{
               fprintf(stderr,"%s:Creating lock file.lck\n",strerror(errno));
               abort();
              }
         }
    }while(fd==-1);
  close(fd);
}
static void
UnLock(void)
{
  unlink("file.lck";
}

int
main(int argc,char **argv)
{
  FILE *f=NULL;
  int i;
  int ch;
  int lck=0;
  if(argc>2&&!strcasecmp(argv[1],"NOLOCK")
     lck=0;
printf("rocess ID %ld started with %s\n",(long)getpid(),lck?"locking":"no locking";
  printf("breakpoint\n";
  for(i=0;i<100;i++)
  {
   if(lck)
   Lock();  
   f=fopen("1.txt","r+";
if(!f&&errno==ENOENT)
  f=fopen("1.txt","w";
  if(!f){
   fprintf(stderr,"%spening file.dat file for r/w\n",strerror(errno));
  if(lck)
    UnLock();
    return 1;
}

  fseek(f,0,SEEK_END);
  fprintf(f,"%05ld i=%06d",(long)getpid(),i);
  for(ch=' ';ch<='z';++ch)
  fputc(ch,f);
  fputc('\n',f);
  fclose(f);
  if(lck)
    UnLock();
}
  printf("rocess ID %ld completed.\n",(long)getpid());
  return 0;
}
在这有个问题,为什么把Lock()方法去掉后,就会出问题呢?大虾们试一试!
小弟对这个Lock()函数起的作用不太清楚,望指教指教!

作者: kellenforever   发布时间: 2010-07-29

Lock()是用来上创建锁文件的.如果锁文件已经存在,Lock()就循环检查知道锁文件不存在了,它就创建一个锁文件并返回.

一般线程同步时才需要锁文件吧.

作者: liwangli1983   发布时间: 2010-07-30

相关阅读 更多

热门下载

更多