第一次用markdown语法写博客,写出来的还比较整齐,感觉博客园对序号的支持不是很好,调了一会才有了比较满意的效果,还有有哪位知道使用markdown如何插入frame?

这边博客主要说了APUE中文件I/O的主要知识点,并且尝试写了一些代码,都列在了博客中。

3.1 文件描述符

对于内核而言,所有打开的文件都通过文件描述符引用。文件描述符是一个非负整数。当打开一个现有文件或创建一个新文件时,内核向进程返回一个文件描述符。当读,写一个文件时,使用open或者creat返回的文件描述符标识该文件,并将其作为参数传递给read或者write。

我们把标准输入(0),标准输出(1)和标准错误(2)文件描述符替换为符号常量STDIN_FINENO,STDOUT_FILENO,STDERR_FILENO,系统支持的最大文件描述符数量可以由以下方式获取:

  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <sys/resource.h>
  4. #include <errno.h>
  5. int main(void)
  6. {
  7. /*****************************
  8. * print file descriptors for
  9. * standard input
  10. * standard output
  11. * standard err
  12. * ***************************/
  13. printf("%d\n",STDIN_FILENO);
  14. printf("%d\n",STDOUT_FILENO);
  15. printf("%d\n",STDERR_FILENO);
  16. //printf("%d\n",OPEN_MAX); OPEN_MAX is deprecated
  17. /*************************************
  18. * how to get the OPEN_MAX value
  19. ************************************/
  20. struct rlimit limit;
  21. if(getrlimit(RLIMIT_NOFILE,&limit)==-1)
  22. perror("getrlimit");
  23. printf("getrlimit=%d\n",(int)limit.rlim_cur);
  24. return 0;
  25. }

3.2 open和openat

使用open和openat可以打开或者创建一个文件,下面是使用open和openat的实例:

  1. #include <fcntl.h>
  2. #include <stdio.h>
  3. #define RWRWRW (S_IRUSR |S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)
  4. int main(void)
  5. {
  6. /*****************************************************************/
  7. //int open(const char*path,int oflag,.../*mode_t mode*/);
  8. //int openat(int fd,const char*path,int oflag,.../*mode_t mode*/)
  9. /****************************************************************/
  10. /*One of the following five flags must be specified:
  11. // O_RDONLY read only
  12. // O_WRONLY write only
  13. // O_RDWR read and write
  14. // most implementations define O_RDONLY as 0,O_WRONLY as 1,
  15. // O_RDWR as 2.
  16. // O_EXEC execute-only
  17. // O_SEARCH search-only\
  18. ****************************************************************/
  19. /*The following ones are optional:
  20. * O_APPEND
  21. * O_CLOEXEC
  22. * O_CREAT
  23. * O_DIRECTORY
  24. * O_EXEL
  25. * O_NOCTTY
  26. * O_NOFOLLOW
  27. * O_NONBLOCK
  28. * O_SYNC
  29. * O_TRUNC
  30. * O_TTY_INIT
  31. * O_DSYNC
  32. * O_RSYNC
  33. * */
  34. int fd = openat(0,"/tmp/test.txt",O_WRONLY|O_CREAT,RWRWRW);//0 is ignored if path is absolute path.
  35. close(fd);
  36. int dir_fd = open("/tmp",O_RDONLY);
  37. printf("%d\n",dir_fd);
  38. fd = openat(dir_fd,"test.txt",O_RDONLY);
  39. printf("%d\n",fd);
  40. fd = open("/tmp/test.txt",O_RDWR);
  41. printf("%d\n",fd);
  42. int rv = write(fd,"test",4);
  43. printf("%d\n",rv);
  44. /*
  45. *Test if a file exists
  46. */
  47. fd = open("/tmp/test.txt",O_CREAT|O_EXCL);
  48. printf("The file exists,so the open result is %d\n",fd);
  49. }

fd参数把open和openat区分开,共有三种可能:

  • path参数指定的是绝对路径名,在这种情况下,fd参数被忽略,openat就相当于open.
  • path参数指定的是相对路径名,fd参数指出了相对路径名在文件系统中的开始地址。fd参数是通过打开相对路径名所在的目录来获取。
  • path参数指定了相对路径名,fd参数具有特殊值AT_FDCWD。在这种情况下,路径名在当前工作目录中获取,openat函数在操作上和open函数类似。

3.3 函数creat

  1. #include <stdio.h>
  2. #include <fcntl.h>
  3. #define RWRWRW (S_IRUSR |S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)
  4. #define RRR (S_IRUSR| S_IRGRP|S_IROTH)
  5. int main(void)
  6. {
  7. /********************************************
  8. * int creat(const char *path,mode_t mode);
  9. * is equal to
  10. * open(path,O_WRONLY|OCREAT|O_TRUNC,mode)
  11. * *****************************************/
  12. int fd = creat("/tmp/creat.txt",RRR);//-r--r--r-- 1 harlan harlan 0 5月 18 21:49 creat.txt.
  13. printf("%d\n",fd);
  14. fd = creat("/tmp/creatRW.txt",RWRWRW);//umask 0002 -rw-rw-r-- 1 harlan harlan 0 5月 18 21:51 creatRW.txt.
  15. printf("%d\n",fd);
  16. return 0;
  17. }

3.4 函数close

关闭一个文件是释放该进程加在文件上的所有记录锁。当一个进程终止时,内核自动关闭它所有的打开文件。

3.5 函数lseek

  1. #include <stdio.h>
  2. #include <fcntl.h>
  3. int main(void)
  4. {
  5. /*
  6. *off_t lseek(int fd,off_t offset,int whence);
  7. * */
  8. int fd = open("/etc/passwd",O_RDONLY);
  9. int len = lseek(fd,0,SEEK_END);
  10. printf("The file /etc/passwd 's length is %d\n",len);
  11. //back to the beginning of the file
  12. int zero = lseek(fd,0,SEEK_SET);
  13. printf("The offset of the beginning of the file is %d\n",zero);
  14. int mid = lseek(fd,len/2,SEEK_CUR);
  15. printf("Move to the middle of the file %d\n",mid);
  16. }

关于lseek函数中参数offset的解释与参数whence的值有关。

若whence是SEEK_SET,则将该文件的偏移量设置为距文件开始处offset个字节。

若whence是SEEK_CUR,则将该文件的偏移量设置为其当前值加offset,offset可为正或负。

若whence是SEEK_END,则将该文件的偏移量设置为文件长度加offset,offset可正可负。

3.6 函数read和write

如果read成功,则返回读到的字节数。如已达到文件的尾端,则返回0。

  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <fcntl.h>
  5. #define RRR (S_IRUSR| S_IRGRP|S_IROTH)
  6. int main(void)
  7. {
  8. /***************************************************
  9. * POSIX.1
  10. * ssize_t read(int fd,void *buf,size_t nbytes)
  11. * ISO_C
  12. * int read(int fd,char *buf,unsigned nbytes);
  13. **************************************************/
  14. int fd = creat("/tmp/read.txt",RRR);
  15. int byteNumWrite = write(fd,"abcdefg",7);
  16. printf("The string \"abcdefg\" is write to read.txt,the real string length wrote to the file is %d\n",
  17. byteNumWrite);//result is 7
  18. close(fd);
  19. fd = open("/tmp/read.txt",O_RDONLY);
  20. char *buf = (char*)malloc(sizeof(char)*8);
  21. ssize_t byteNumRead = read(fd,buf,8);
  22. printf("The bytes read from read.txt is %d\n",(int)byteNumRead);//print result is 7
  23. close(fd);
  24. return 0;
  25. }

3.7 文件共享

内核使用三种数据结构表示打开文件,它们之间的关系决定了在文件共享方面一个进程对另一个进程可能产生的影响。

  • 每个进程在进程表中都有一个记录项,记录项中包含一张打开文件描述符表,可将其视为一个矢量,每个描述符占用一项。于每个文件描述符相关联的是:

    1. 文件描述符标志(close_on_exec);
    2. 指向一个文件表项的指针。
  • 内核为所有打开文件维持一张文件表。每个文件表项包含:
    1. 文件状态标志;
    2. 当前文件偏移量;
    3. 指向该文件V节点表项的指针。
  • 每个打开文件(或设备)都有一个V节点(v-node)结构。

见下图:

如果两个独立进程各自打开了同一文件,则有下面的关系图:


3.8 原子操作

pread是一个原子操作,它用来执行定位并执行I/O,pread相当于调用lseek后调用read,但pread与这种调用顺序有区别。

  • 调用pread时,无法中断其定位和读操作。
  • 不更新当前文件偏移量。(见下面的例子)
  1. #include <unistd.h>
  2. #include <fcntl.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #define RRR (S_IRUSR| S_IRGRP|S_IROTH)
  6. off_t getCurOffset(int fd)t
  7. {
  8. return lseek(fd,0,SEEK_CUR);
  9. }
  10. void printCurOffset(int fd)*
  11. {
  12. printf("the current file offset is %d\n",(int)getCurOffset(fd));
  13. }
  14. int main(void)
  15. {
  16. /*****************************************************************
  17. *ssize_t pread(int fd,void *buf,size_t nbytes,off_t offset);
  18. *pread will not update the current file offset,see the following examples
  19. *ssize_t pwrite(int fd,const void * buf,size_t nbytes,off_t offset);
  20. *******************************************************************/
  21. int fd = creat("/tmp/pread.txt",RRR);
  22. int writeBytes = write(fd,"abcdefghij",10);
  23. close(fd);
  24. fd = open("/tmp/pread.txt",O_RDONLY);
  25. printCurOffset(fd);
  26. char *buf = (char*)malloc(5);
  27. ssize_t readBytes = pread(fd,buf,4,2);
  28. buf[4]='\0';
  29. printf("Read %d bytes:%s\n",(int)readBytes,buf);
  30. printCurOffset(fd);
  31. return 0;
  32. }

3.9 函数dup和dup2

dup和dup2都用来复制一个现有的文件描述符。对于dup2,可以自己指定新描述符的值,如果新描述符的值已经打开,则现将其关闭。如果新旧描述符值相等,则直接返回旧描述符值。如果不等,新描述符的FD_CLOEXEC文件描述符标志就会被清除(见下例)。

  1. #include <stdio.h>
  2. int main(int argc,char *argv[])
  3. {
  4. if(2!=argc)
  5. {
  6. printf("The parameter number is not correct!");
  7. }
  8. //get the file descriptor
  9. int fd = atoi(argv[1]);
  10. char buf[100]={0};
  11. int NumReadBytes = read(fd,buf,5);
  12. printf("The number of byte %d: %s\n",NumReadBytes,buf);
  13. }

上面代码命名为read.c,执行下面的命令生成read可执行文件

  1. gcc read.c -o read
  1. #include <fcntl.h>
  2. #include <unistd.h>
  3. #include <sys/stat.h>
  4. #include <stdio.h>
  5. #define RRR (S_IRUSR| S_IRGRP|S_IROTH)
  6. #define RWRWRW (S_IRUSR|S_IWUSR| S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)
  7. void printfdInfo(int fd)
  8. {
  9. printf("fd num %d\n",fd);
  10. printf("get FL of /etc/passwd %d\n",fcntl(fd,F_GETFL));
  11. printf("get FD of /etc/passwd %d\n",fcntl(fd,F_GETFD));
  12. }
  13. void execRead(int fd)
  14. {
  15. char fdString[4]={0};
  16. sprintf(fdString,"%d",fd);
  17. int pid = 0;
  18. int status = 0;
  19. if((pid=fork()) != 0)//father process
  20. {
  21. //wait for child process finish
  22. waitpid(pid,&status,0);
  23. }
  24. else//child process
  25. {
  26. if(execl("read",fdString,NULL)<0)//fd is open in child process
  27. perror("issue read failed.");
  28. }
  29. }
  30. void test_FD_CLOEXEC()
  31. {
  32. //open success
  33. int fd = open("/etc/passwd",O_RDONLY);
  34. printfdInfo(fd);//fd is 0
  35. execRead(fd);//read success
  36. fcntl(fd,F_SETFD,FD_CLOEXEC);
  37. printfdInfo(fd);//fd is 1,the fd is closed in child process.
  38. execRead(fd);//read failed
  39. close(fd);
  40. }
  41. void test_dup()
  42. {
  43. int fd = open("/etc/passwd",O_RDONLY);
  44. int dupfd = dup(fd);
  45. //FD and FL are all the same.
  46. printfdInfo(fd);
  47. printfdInfo(dupfd);
  48. }
  49. void test_dup2()
  50. {
  51. int fd = open("/etc/passwd",O_RDONLY);
  52. fcntl(fd,F_SETFD,FD_CLOEXEC);
  53. int newfd = dup2(fd,13);
  54. execRead(fd);//read failed,fd is closed.
  55. execRead(newfd);//the FD_CLOEXEC is cleared.
  56. close(fd);
  57. close(newfd);
  58. }
  59. int main(void)
  60. {
  61. printf("test_FD_CLOEXEC.....................\n");
  62. test_FD_CLOEXEC();
  63. printf("test_dup.....................\n");
  64. test_dup();
  65. printf("test_dup2.....................\n");
  66. test_dup2();
  67. return 0;
  68. }

3.10 函数fcntl

fcntl函数可以改变已经打开文件的属性。fcntl函数有以下5种功能:

  1. 复制一个已有的文件描述符(cmd=F_DUPFD)
  2. 获取/设置文件描述符标志(cmd=F_GETFD或者F_SETFD)
  3. 获取/设置文件状态标志(cmd=F_GETFL或者F_SETFL)
  4. 获取设置异步i/o所有权(cmd=F_GETOWN或者F_SETOWN)
  5. 或者/设置记录锁(cmd=F_GETLK,F_SETLK或F_SETLKW)

下面是几个例子:

  1. #include <fcntl.h>
  2. #include <stdio.h>
  3. #include <sys/stat.h>
  4. void printFD(int fd)
  5. {
  6. printf("The fd num is %d\n",fd);
  7. }
  8. void printFDFlags(int fd,int fdflags)
  9. {
  10. printf("The file description flags of %d is %d\n",fd,fdflags);
  11. }
  12. void printFLFlags(int fd,int flflags)
  13. {
  14. printf("The file status flags of %d is %d\n",fd,flflags);
  15. }
  16. void F_DUPFD_fcntl()
  17. {
  18. printf("F_DUPFD_fcntl()..........\n");
  19. int fd = open("/etc/passwd",O_RDONLY);
  20. int newfd = fcntl(fd,F_DUPFD,0);//equal to dup(fd)
  21. printFD(fd);
  22. printFD(newfd);
  23. close(fd);
  24. close(newfd);
  25. }
  26. /*void F_DUPFD_CLOEXEC_fcntl()
  27. {
  28. int fd = open("/etc/passwd",O_RDONLY);
  29. int newfd = fcntl(fd,F_DUPFD_CLOEXEC,0);
  30. int fdI = fcntl(fd,F_GETFD,0);
  31. printFDI(fd,fdI);
  32. int newfdI = fcntl(newfd,F_GETFD,0);
  33. printFDI(newfd,newfdI);
  34. }*/
  35. void F_SET_FD_GET_FD_fcntl()
  36. {
  37. printf("F_SETFD_GETFD_fcntl()..........\n");
  38. int fd = open("/etc/passwd",O_RDONLY);
  39. int fdflag = fcntl(fd,F_GETFD,0);
  40. printFDFlags(fd,fdflag);
  41. fcntl(fd,F_SETFD,1);
  42. fdflag = fcntl(fd,F_GETFD,0);
  43. printFDFlags(fd,fdflag);
  44. }
  45. /*********************************************************
  46. * note this command can change only the O_APPEND,
  47. * O_ASYNC, O_DIRECT, O_NOATIME, and O_NONBLOCK flags
  48. *******************************************************/
  49. #define RWRWRW (S_IRUSR|S_IWUSR| S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)
  50. void F_SETFL_GETFL_fcntl()
  51. {
  52. printf("F_SETFL_GETFL_fcntl()..........\n");
  53. int fd = open("/etc/passwd",O_RDONLY);
  54. int flflag = fcntl(fd,F_GETFL);
  55. printFLFlags(fd,flflag);
  56. fcntl(fd,F_SETFL,O_APPEND);
  57. flflag = fcntl(fd,F_GETFL);
  58. printFLFlags(fd,flflag);
  59. }
  60. int main(void)
  61. {
  62. /**********************************************/
  63. /* int fcntl(int fd,int cmd,...*//* int arg*///)
  64. /**********************************************/
  65. F_DUPFD_fcntl();
  66. //F_DUPFD_CLOEXEC_fcntl();
  67. F_SET_FD_GET_FD_fcntl();
  68. F_SETFL_GETFL_fcntl();
  69. return 0;
  70. }

UNIX文件I/O的更多相关文章

  1. Unix文件操作

    一.概述 Unix文件操作常用函数包括open.close.creat.lseek.dup.dup2.fcntl等, 其中open.creat. fcntl函数需要包含头文件<fcntl.h&g ...

  2. UNIX文件的权限之“设置用户ID位”

    用stat函数可以获取一个文件的状态信息,原型是这样的: int stat(const char *path, struct stat *buf); 其中结构体stat的结构: struct stat ...

  3. unix文件操作函数

    1. fopen函数 #include <stdio.h> FILE *fopen(const char *path, const char *mode) 返回:文件顺利打开后,指向该流的 ...

  4. unix文件权限

    一.UNIX下关于文件权限的表示方法和解析 SUID 是 Set User ID, SGID 是 Set Group ID的意思. UNIX下可以用ls -l 命令来看到文件的权限.用ls命令所得到的 ...

  5. Unix文件 I/O(不带缓冲区的)上

    简介 Unix系统大多数文件i/o只需要:open.read.write.lseek.close这几个函数.但是某些时候我们也需要fcntl.ioctl.sync等函数配合使用.这些函数都是不带缓冲区 ...

  6. 使用UltraEdit实现从DOS文件到UNIX文件的批量转换

    最近把公司从SVN切到GIT下,因为大多同事在Windows下开发,又碰到换行符问题,找到一个批量转换方法 打开UE->在文件中替换,把^p替换成^n,然后设置好要替换的文件和路径,就开始替换吧 ...

  7. dos文件批量转换成unix文件

    对于经常在windows环境下和linux环境同时使用的文件(如在windows系统下编写,在linux环境下编译的文件), 常常存在这样的问题:由于两种系统的格式文件格式不同,导致程序出现不期望的问 ...

  8. Unix - 文件中构成一个空洞的分析

    lseek函数显示地为一个打开文件设置偏移量,文件偏移量可以大于文件的当前长度,在这种情况下,对该文件的下一次写将加长该文件,并在文件中构成一个空洞,这一点是允许的.位于文件中但没有写过的字节都被读为 ...

  9. UNIX文件mode_t详解 ... S_IRUSR

    打开文件.新建文件和关闭文件操作 打开文件操作使用系统调用函数open(),该函数的作用是建立一个文件描述符,其他的函数可以通过文件描述符对指定文件进行读取与写入的操作.打开文件的一般形式是: ope ...

随机推荐

  1. 1163: 零起点学算法70——Yes,I can!

    1163: 零起点学算法70--Yes,I can! Time Limit: 1 Sec  Memory Limit: 64 MB   64bit IO Format: %lldSubmitted: ...

  2. MCDownloader(iOS下载器)说明书

    示例 前言 很多iOS应用中都需要下载数据,并对这些下载的过程和结果进行管理,因此我才有了写这个MCDownloader的想法.在IOS 文件下载器-MCDownloadManager这篇文章中,我使 ...

  3. python的MySQLdb模块在linux环境下的安装

    开始学习python数据库编程后,在了解了基本概念,打算上手试验一下时,卡在了MYSQLdb包的安装上,折腾了半天才解决.记录一下我在linux中安装此包遇到的问题.系统是ubuntn15.04. 1 ...

  4. --save 和 --save-dev的区别

    --save是对生产环境所需依赖的声明(开发应用中使用的框架,库,比如jquery,bootstrap等) --save-dev是对开发环境所需依赖的声明(构建工具,测试工具,比如babel,gulp ...

  5. 《Algorithms Unlocked》读书笔记2——二分查找和排序算法

    <Algorithms Unlocked>是 <算法导论>的合著者之一 Thomas H. Cormen 写的一本算法基础,算是啃CLRS前的开胃菜和辅助教材.如果CLRS的厚 ...

  6. android studio 2.3 下载地址

      android studio下载:  Windows+SDK:(1.8GB)| Windows(428 MB) | Linux    idea  win.exe  win.zip 序号 名称 中文 ...

  7. 第三章 PL/SQL编程

    3.1 PL/SQL基础知识    3.1.1 什么是PL/SQL?        PL/SQL是结合Oracle过程语言和结构化查询语言的一种扩展语言        3.1.1.1 PL/SQL体系 ...

  8. CSS清除float浮动

    一.浮动产生原因   -   TOP 一般浮动是什么情况呢?一般是一个盒子里使用了CSS float浮动属性,导致父级对象盒子不能被撑开,这样CSS float浮动就产生了. 本来两个黑色对象盒子是在 ...

  9. cocos2d-x - C++/Lua交互

    使用tolua++将自定义的C++类嵌入,让lua脚本使用 一般过程: 自定义类 -> 使用tolua++工具编译到LuaCoco2d.cpp中 -> lua调用 步骤一:自定义一个C++ ...

  10. CF #284 div1 D. Traffic Jams in the Land 线段树

    大意是有n段路,每一段路有个值a,通过每一端路需要1s,如果通过这一段路时刻t为a的倍数,则需要等待1s再走,也就是需要2s通过. 比较头疼的就是相邻两个数之间会因为数字不同制约,一开始想a的范围是2 ...