文件I/O实践(3) --文件共享与fcntl

文件共享


一个进程打开了两个文件

文件表条目(file-table-entry):

   1.文件状态标志(file-status-flags): 读/写/追加/同步/非阻塞等;

   2.当前文件偏移量

   3.v节点指针


[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //验证  
  2. int main(int argc, char *argv[])  
  3. {  
  4.     int fd1 = open("test.txt", O_RDONLY);  
  5.     if (fd1 == -1)  
  6.         err_exit("fd1 open O_RDONLY error");  
  7.     int fd2 = open("test.txt", O_RDWR);  
  8.     if (fd2 == -1)  
  9.         err_exit("fd2 open O_RDWR error");  
  10.   
  11.     //读取fd1  
  12.     char buf[BUFSIZ];  
  13.     if (read(fd1, buf, 10) == -1)  
  14.         err_exit("read fd1 error");  
  15.     cout << "fd1: " << buf << endl;  
  16.   
  17.     //读取fd2  
  18.     bzero(buf, 10);  
  19.     if (read(fd2, buf, 10) == -1)  
  20.         err_exit("read fd1 error");  
  21.     cout << "fd2: " << buf << endl;  
  22.   
  23.     lseek(fd1, 0, SEEK_SET);  
  24.     lseek(fd2, 0, SEEK_SET);  
  25.     write(fd2, "Helloworld", 10);  
  26.     bzero(buf, 10);  
  27.     if (read(fd1, buf, 10) == -1)  
  28.         err_exit("read fd1 error");  
  29.     cout << "after fd2 write: " << buf << endl;  
  30. }  


两个独立的进程打开同一个文件

复制文件描述符

 

方法有三种:

1.dup

2.dup2 

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #include <unistd.h>  
  2. int dup(int oldfd);  
  3. int dup2(int oldfd, int newfd);  
[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //示例  
  2. int main(int argc, char *argv[])  
  3. {  
  4.     int fd = open("text.txt", O_WRONLY|O_TRUNC);  
  5.     if (fd == -1)  
  6.         err_exit("open O_WRONLY error");  
  7.   
  8. //    close(1);   //将标准输出关闭, 则文件描述符1将空闲  
  9. //    int dupfd = dup(fd);  
  10.     int dupfd = dup2(fd, 1);  
  11.     cout << "dupfd = " << dupfd << endl;  
  12. }  
[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /** 示例: 实现文件拷贝 
  2. 其中execlp会在后面介绍 
  3. **/  
  4. int main(int argc, char *argv[])  
  5. {  
  6.     if (argc < 3)  
  7.         err_quit("usage: ./main file-name1 file-name2");  
  8.   
  9.     close(STDIN_FILENO);  
  10.     open(argv[1], O_RDONLY);  
  11.     close(STDOUT_FILENO);  
  12.     open(argv[2], O_WRONLY|O_CREAT, 0666);  
  13.   
  14.     execlp("/bin/cat""cat", NULL);  
  15.     err_exit("execlp error");  
  16. }  
3.fcntl
[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. int fcntl(int fd, F_DUPFD, ... /* arg */ );  
  2. //示例见下  

fcntl

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #include <unistd.h>  
  2. #include <fcntl.h>  
  3. int fcntl(int fd, int cmd, ... /* arg */ );  

  操纵文件描述符, 改变已经打开的文件的属性

fcntl常用操作(cmd常用取值)

F_DUPFD (long)

复制文件描述符

 

F_GETFD (void)

F_SETFD (long)

文件描述符标志

 

F_GETFL (void)

F_SETFL (long)

文件状态标志

 

F_GETLK

F_SETLK,F_SETLKW(阻塞)

文件锁

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //示例: 复制文件描述符  
  2. int main(int argc, char *argv[])  
  3. {  
  4.     int fd = open("text.txt", O_WRONLY|O_TRUNC);  
  5.     if (fd == -1)  
  6.         err_exit("open O_WRONLY error");  
  7.   
  8.     close(1);   //将标准输出关闭, 则文件描述符1将空闲  
  9.     // 当cmd使用F_DUPFD时, 第三个参数代表搜索的起始位置  
  10.     int dupfd = fcntl(fd, F_DUPFD, 1);  // 1代表: 从1开始搜索一个空闲的文件描述符  
  11.     if (dupfd < 0)  
  12.         err_exit("fcntl F_DUPFD error");  
  13.     cout << "dupfd = " << dupfd << endl;  
  14. }  

文件状态标志

F_GETFL (void)

 Get the file access mode and the file status flags; arg is ignored.

F_SETFL (int)

 Set the file status flags to  the  value  specified  by  arg.   File  access  mode(O_RDONLY,  O_WRONLY,  O_RDWR)  and  file  creation  flags (i.e., O_CREAT, O_EXCL, O_NOCTTY, O_TRUNC) in arg are ignored.  On Linux this command can change only  the O_APPEND, O_ASYNC, O_DIRECT, O_NOATIME, and O_NONBLOCK flags.

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //示例: 给文件描述符0设置成非阻塞模式  
  2. int main(int argc, char *argv[])  
  3. {  
  4.     int flags = fcntl(0, F_GETFL, 0);  
  5.     if (flags == -1)  
  6.         err_exit("fcntl get error");  
  7.     flags |= O_NONBLOCK;  
  8.     if (fcntl(0, F_SETFL, flags) == -1)  
  9.         err_exit("fcntl set error");  
  10.   
  11.     char buf[BUFSIZ];  
  12.     if (read(0, buf, sizeof(buf)) == -1)  
  13.         err_exit("read STDIN_FILENO error");  
  14.     cout << "buffer size = " << strlen(buf) << endl;  
  15.     cout << buf << endl;  
  16. }  
[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //示例: 文件状态设置与清除(函数封装)  
  2. void set_fl(int fd, int setFlag)  
  3. {  
  4.     int flags = fcntl(fd, F_GETFL, 0);  
  5.     if (flags == -1)  
  6.         err_exit("fcntl get flags error");  
  7.     //设置状态  
  8.     flags |= setFlag;  
  9.     if (fcntl(fd, F_SETFL, flags) == -1)  
  10.         err_exit("fcntl set flags error");  
  11. }  
  12. void clr_fl(int fd, int clrFlag)  
  13. {  
  14.     int flags = fcntl(fd, F_GETFL, 0);  
  15.     if (flags == -1)  
  16.         err_exit("fcntl get flags error");  
  17.     //清除状态  
  18.     flags &= ~clrFlag;  
  19.     if (fcntl(fd, F_SETFL, flags) == -1)  
  20.         err_exit("fcntl set flags error");  
  21. }  
  22.   
  23. //测试  
  24. int main(int argc, char *argv[])  
  25. {  
  26.     set_fl(0, O_NONBLOCK);  
  27.     clr_fl(0, O_NONBLOCK);  
  28.     char buf[BUFSIZ];  
  29.     if (read(0, buf, sizeof(buf)) == -1)  
  30.         err_exit("read STDIN_FILENO error");  
  31.     cout << "buffer size = " << strlen(buf) << endl;  
  32.     cout << buf << endl;  
  33. }  

文件锁

F_SETLK (struct flock *)

 Acquire  a lock (when l_type is F_RDLCK or F_WRLCK) or release a lock (when l_type is F_UNLCK) on the bytes specified by the l_whence, l_start, and l_len  fields  of lock.   If a conflicting lock is held by another process, this call returns -1 and sets errno to EACCES or EAGAIN.

F_SETLKW (struct flock *) 如果加锁不成功:会一直阻塞直到解锁

 As for F_SETLK, but if a conflicting lock is held on the file, then wait for  that lock to be released.  If a signal is caught while waiting, then the call is interrupted and (after the signal  handler  has  returned)  returns  immediately  (with return value -1 and errno set to EINTR; see signal(7)).

F_GETLK (struct flock *)

 On  input  to this call, lock describes a lock we would like to place on the file.

 If the lock could be placed, fcntl() does  not  actually  place  it,  but  returns F_UNLCK  in  the l_type field of lock and leaves the other fields of the structure unchanged.  If one or more  incompatible  locks  would  prevent  this  lock  being placed,  then  fcntl()  returns  details  about  one of these locks in the l_type, l_whence, l_start, and l_len fields of lock and sets l_pid to be the  PID  of  the process holding that lock.

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //文件锁结构体  
  2. struct flock  
  3. {  
  4.     ...  
  5.     short l_type;    /* Type of lock: F_RDLCK, 
  6.                                    F_WRLCK, F_UNLCK */  
  7.     short l_whence;  /* How to interpret l_start: 
  8.                                    SEEK_SET, SEEK_CUR, SEEK_END */  
  9.     off_t l_start;   /* Starting offset for lock */  
  10.     off_t l_len;     /* Number of bytes to lock */  
  11.     pid_t l_pid;     /* PID of process blocking our lock 
  12.                                    (F_GETLK only) */  
  13.     ...  
  14. };  

注意: Specifying 0 for l_len has the special meaning: lock all bytes starting  at  

the  location  specified  by l_whence and l_start through to the end of file, 

no matter how large the file grows.

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //示例1  
  2. int main(int argc, char *argv[])  
  3. {  
  4.     int fd = open("test.txt", O_RDWR|O_CREAT|O_TRUNC, 0666);  
  5.     if (fd == -1)  
  6.         err_exit("open file error");  
  7.   
  8.     struct flock lock;  
  9.     lock.l_type = F_WRLCK;  //设定独占锁  
  10.     lock.l_whence = SEEK_SET;  
  11.     lock.l_start = 0;  
  12.     lock.l_len = 0; //锁定全部文件  
  13.   
  14.     //if (fcntl(fd, F_SETLK, &lock) == 0)   //对比下面  
  15.     if (fcntl(fd, F_SETLKW, &lock) == 0)  
  16.     {  
  17.         cout << "file lock success, press any key to unlock..." << endl;  
  18.         cin.get();  
  19.   
  20.         lock.l_type = F_UNLCK;  
  21.         lock.l_whence = SEEK_SET;  
  22.         lock.l_start = 0;  
  23.         lock.l_len = 0;  
  24.         if (fcntl(fd, F_SETLK, &lock) == -1)  
  25.             err_exit("file unlock error");  
  26.         else  
  27.             cout << "file unlock success" << endl;  
  28.     }  
  29.     else  
  30.         err_exit("file lock error");  
  31. }  
[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //示例2: 打印加锁进程号  
  2. int main(int argc, char *argv[])  
  3. {  
  4.     int fd = open("test.txt", O_RDWR|O_CREAT|O_TRUNC, 0666);  
  5.     if (fd == -1)  
  6.         err_exit("open file error");  
  7.   
  8.     struct flock lock;  
  9.     lock.l_type = F_WRLCK;  //设定独占锁  
  10.     lock.l_whence = SEEK_SET;  
  11.     lock.l_start = 0;  
  12.     lock.l_len = 0; //锁定全部文件  
  13.   
  14.     if (fcntl(fd, F_SETLK, &lock) == 0)  
  15.     {  
  16.         cout << "file lock success, press any key to unlock..." << endl;  
  17.         cin.get();  
  18.   
  19.         lock.l_type = F_UNLCK;  
  20.         lock.l_whence = SEEK_SET;  
  21.         lock.l_start = 0;  
  22.         lock.l_len = 0;  
  23.         if (fcntl(fd, F_SETLK, &lock) == -1)  
  24.             err_exit("file unlock error");  
  25.         else  
  26.             cout << "file unlock success" << endl;  
  27.     }  
  28.     else    //如果失败, 则获取锁信息  
  29.     {  
  30.         if (fcntl(fd, F_GETLK, &lock) == -1)  
  31.             err_exit("get lock error");  
  32.   
  33.         cout << "lock process: " << lock.l_pid << endl;  
  34.         if (lock.l_type == F_WRLCK)  
  35.             cout << "type: F_WRLCK" << endl;  
  36.         else  
  37.             cout << "type: F_RDLCK" << endl;  
  38.   
  39.         if (lock.l_whence == SEEK_SET)  
  40.             cout << "whence: SEEK_SET" << endl;  
  41.         else if (lock.l_whence == SEEK_END)  
  42.             cout << "whence: SEEK_END" << endl;  
  43.         else  
  44.             cout << "whence: SEEK_CUR" << endl;  
  45.     }  
  46. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值