实验1

来源:互联网 发布:java注释声明 编辑:程序博客网 时间:2024/05/21 20:21

#include <stdio.h>

int main()

{

  printf("hello world");

  return 0;

}

 

#include <stdio.h>

#include <sys/types.h>

#include <unistd.h>

#include <fcntl.h>

#include <sys/stat.h>

#include <stdlib.h>

/*struct flock

{

  short 1_type;

  off_t 1_start;

  short 1_whence;

  off_t 1_len;

  pid_t 1_pid;

}old_lock,lock;*/

 

int lock_set(int fd,int type)

{

  struct flock old_lock,lock;

  lock.l_whence = SEEK_SET;  //相对位移量的起点:当前位置为文件开头

  lock.l_start = 0;     //加锁区域的相对位移量

  lock.l_len = 0;     //加锁区域长度

  lock.l_type = type;   //锁的类型

  lock.l_pid = -1;      //记录持有锁的进程

 

  fcntl(fd,F_GETLK,&lock);  //fd;根据参数3决定文件是否上锁;struct flock:记录锁的具体状态   总:判断文件是否可以上锁

  if(lock.l_type != F_UNLCK)

   {

     if(lock.l_type == F_RDLCK)    //读取锁(共享锁)

     {

         printf("Read lock already set by %d\n",lock.l_pid);

     }

     else if(lock.l_type == F_WRLCK)   //写入锁(排斥锁)

     {

         printf("Write lock already set by %d\n",lock.l_pid);

     }

   }

 

lock.l_type = type;   //l_type的值可能已被F_GETLK修改过

 

if((fcntl(fd,F_SETLKW,&lock)) < 0)    //阻塞式上锁

{

  printf("Lock failed:type = %d\n",lock.l_type);

  return 1;

}

 

switch(lock.l_type)

{

  case F_RDLCK:

   {

     printf("Read lock set by %d\n",getpid());

   }

  break;

  case F_WRLCK:

   {

      printf("Write lock set by%d\n",getpid());

   }

  break;

  case F_UNLCK:

   {

     printf("Release lock by %d\n",getpid());

     return 1;

   }

  break;

  default:

  break;

}

  return 0;

}

 

写入锁函数1:

int main(void)

{

   int fd;

   fd = open("hello.c",O_RDWR|O_CREAT,0644);

   if(fd<0)

   {

      printf("open file error\n");

      exit(1);

   }

 

   lock_set(fd,F_WRLCK);   //给文件写入锁

   getchar();

 

   lock_set(fd,F_UNLCK);   //给文件解锁

   getchar();

 

   close(fd);

   exit(0);

 

读取锁函数2:

int main(void)

{

   int fd;

   fd =open("hello.c",O_RDWR|O_CREAT,0644);

   if(fd<0)

   {

      printf("open file error\n");

      exit(1);

   }

 

   lock_set(fd,F_RDLCK);//给文件读取锁

   getchar();

 

   lock_set(fd,F_UNLCK);//给文件解锁

   getchar();

 

   close(fd);

   exit(0);

}

}
0 0