实验 5.2.8-3 对文件的任意部分加锁 1. 用 fcntl()对文件进行锁操作。 2. 完善课件中的示例程序,给出程序运行结果及分析。 给b.txt中的前10个字节加写锁

实验 5.2.8-3 对文件的任意部分加锁
1. 用 fcntl()对文件进行锁操作。
2. 完善课件中的示例程序,给出程序运行结果及分析。
给b.txt中的前10个字节加写锁
#include<stdio.h>
 #include<stdlib.h> 
#include<unistd.h> 
#include<sys/types.h> 
#include<sys/stat.h> 
#include<fcntl.h> 
#include<string.h>  
 int main() 
{      
char arr[]="Good good study,day day up!";       //创建或打开一个文件     
 int fd=open("a.txt",O_RDWR|O_CREAT|O_TRUNC,0664);     
if(-1==fd)     {        
  perror("open");         
exit(-1);     }   
   printf("文件打开成功\n");       //写入文件    
  int res=write(fd,arr,strlen(arr));    
 if(-1==res)     {     
     perror("write");       
  exit(-1);     }   
   printf("文件写入成功\n");      //准备一把写锁  
   struct flock lock;    
 lock.l_type=F_WRLCK;   
  lock.l_whence=SEEK_SET;   
  lock.l_start=0;
     lock.l_len=10;   
  lock.l_pid=0;
//为文件上锁      
res=fcntl(fd,F_SETLK,&lock);     
if(-1==res)     {        
  perror("fcntl");      
   exit(-1);
}     
 printf("加锁成功,正在关闭文件...\n");
//进程占用  
   sleep(5);     
  //关闭文件,文件锁自动释放  
   res=close(fd);    
 if(-1==res)     {   
       perror("close");     
exit(-1);   
  }    
  printf("文件成功关闭\n");   
    return 0;
 }

#include<stdio.h> 
#include<stdlib.h>
 #include<unistd.h>
 #include<sys/types.h>
 #include<sys/stat.h>
 #include<fcntl.h> 
  int main() {   
   //1.打开文件     
 int fd=open("b.txt",O_WRONLY);
     if(-1==fd)     {     
     perror("open");     
    exit(-1); 
    }    
  printf("成功打开文件\n");    
 //2.写入内容    
  int res=write(fd,"NARUKAKA",9);  
   if(-1==res)    
 {         
 perror("write");   
      exit(-1);   
  }     
 printf("成功写入数据,共写入%d字节\n",res);
//3.关闭文件     res=close(fd); 
    if(-1==res)     {        
  perror("close");    
     exit(-1);   
  }    
  printf("成功关闭文件\n");      
 return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值