LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 768|回复: 1

关于锁机制

[复制链接]
发表于 2006-3-16 22:20:04 | 显示全部楼层 |阅读模式
linux操作系统是不是提供一种对打开文件的锁机制?
如果是的话,是不是fcntl函数在对打开文件进行锁的时候,就没有什么作用了?
这个函数还有什么其它的独特之处吗?若能举例则更好了,顺便帮看一下这个程序
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <unistd.h>
#include <fcntl.h>
int test(int fd,struct flock *lock)
{
  //struct flock lock;
  int stat=fcntl(fd,F_GETLK,lock);
  if (stat<0)
  {
    perror("getlock failed");
    return 0;
  }
  if (stat=0&&(*lock).l_type==F_UNLCK)
  {
    fprintf(stdout,"the file has not locked\n");
    return 1;
  }
  if (stat=0&&(*lock).l_type==(F_WRLCK|F_RDLCK))
  {
      fprintf(stdout,"the file has lock by pid %d\n",(*lock).l_pid);
    return 2;
  }

}
int main()
{
  int fd;
  struct flock lock;
  fd=open("/root/ch11/fcntl/lockit.c",O_RDONLY|O_WRONLY,0644);
  if(fd<0)
  {
    fprintf(stdout,"open file failed\n");
    perror("open");
  }
  int stat=test(fd,&lock);
  switch(stat)
  {
    case 0:break;
    case 1:
    {
      lock.l_type=F_RDLCK;
      lock.l_whence=SEEK_SET;
      lock.l_start=0;
      lock.l_len=1;
      int temp=fcntl(fd,F_SETLK,&lock);
      if(temp<0)
      {
        perror("add read lock");
        exit(EXIT_FAILURE);
      }
      fprintf(stdout,"lock the beginning charater\n");
      break;
    }
    case 2:
    {
      int temp;
      temp=fcntl(fd,F_UNLCK);
      if (temp<0)
      {
        perror("unlock");
        exit(EXIT_FAILURE);
       }
      fprintf(stdout,"unlock success\n");
      break;
    }
    default:
      break;
  }
  close(fd);
  exit(EXIT_FAILURE);
}
这个程序可以编译和执行,但是就是提示fcntl的参数不对,为什么??
发表于 2006-3-17 11:12:43 | 显示全部楼层
man fcntl:

  1.    Advisory locking
  2.        F_GETLK,  F_SETLK  and  F_SETLKW are used to acquire, release, and test
  3.        for the existence of record locks (also known as file-segment or  file-
  4.        region  locks).   The  third  argument lock is a pointer to a structure
  5.        that has at least the following fields (in unspecified order).

  6.          struct flock {
  7.              ...
  8.              short l_type;    /* Type of lock: F_RDLCK,
  9.                                  F_WRLCK, F_UNLCK */
  10.              short l_whence;  /* How to interpret l_start:
  11.                                  SEEK_SET, SEEK_CUR, SEEK_END */
  12.              off_t l_start;   /* Starting offset for lock */
  13.              off_t l_len;     /* Number of bytes to lock */
  14.              pid_t l_pid;     /* PID of process blocking our lock
  15.                                  (F_GETLK only) */
  16.              ...
  17.          };
复制代码
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表