当前位置:   article > 正文

六、Linux系统编程-文件和IO(四)文件共享、复制文件描述符_6://复制所有描述#*fd015a5b17*#后到 app

6://复制所有描述#*fd015a5b17*#后到 app

一、文件共享

每个进程都有一个自己的文件描述符表。在一个进程中,一个文件被打开之后,会分配一个文件描述符,一个文件表表项,一个v节点表。其中文件表保存文件状态,包括:读、写、追加、同步、非阻塞等。其中文件表项是不能共享的,文件被打开一次,就会分配一个文件表项;v节点表示可以共享的,两个不同的文件表项可以指向同一个v节点表。

(1)、一个进程打开两个文件模型



(2)、一个进程两次打开同一个文件



我们可以通过例子证明上面的模型,示例:

  1. #include <string.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <errno.h>
  5. #include <unistd.h>
  6. #define ERR_EXIT(m) \
  7. do \
  8. { \
  9. perror(m); \
  10. exit(EXIT_FAILURE); \
  11. }while(0)
  12. int main()
  13. {
  14. int fd1,fd2;
  15. char buf[1024];
  16. fd1 = open("aa.txt",O_RDWR);
  17. if (fd1 == -1)
  18. ERR_EXIT("open error");
  19. read(fd1,buf,5);
  20. printf("read1:%s\n",buf);
  21. fd2 = open("aa.txt",O_RDWR);
  22. if(fd2 == -1)
  23. ERR_EXIT("open error");
  24. read(fd2,buf,5);
  25. printf("read2:%s\n",buf);
  26. write(fd1,"AAAaa",5);
  27. read(fd2,buf,5);
  28. printf("read fd2:%s\n",buf)
  29. close(fd1);
  30. close(fd2);
  31. return 0;
  32. }
执行结果:

  1. s@ubuntu:~/sys$ cat aa.txt
  2. abcdeAAAaa
  3. s@ubuntu:~/sys$ gcc open2.c
  4. s@ubuntu:~/sys$ ./a.out
  5. read1:abcde
  6. read2:abcde
  7. read fd2:AAAaa
  8. s@ubuntu:~/sys$
说明一个进程打开两次的相同文件会有两个文件表项,但是共享v节点。

(3)、两个进程打开同一个文件


两个进程打开一个文件描述符可以相同,因为每个进程都有自己的文件描述符表。示例:

  1. #include <sys/types.h>
  2. #include <sys/stat.h>
  3. #include <fcntl.h>
  4. #include <string.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <errno.h>
  8. #include <unistd.h>
  9. #define ERR_EXIT(m) \
  10. do \
  11. { \
  12. perror(m); \
  13. exit(EXIT_FAILURE); \
  14. }while(0)
  15. #define MAJOR(a) (int)((unsigned short)a>>8)
  16. #define MINOR(a) (int)((unsigned short)a & 0xFF)
  17. int filetype(struct stat *buf);
  18. int main(int argc,char* argv[])
  19. {
  20. int infd;
  21. int outfd;
  22. int ret;
  23. if ((ret = fork()) > 0)
  24. {
  25. infd = open("aa.txt",O_RDONLY);
  26. printf("in:%d\n",infd);
  27. }
  28. else
  29. {
  30. outfd = open("aa.txt",O_WRONLY);
  31. printf("out:%d\n",outfd);
  32. }
  33. wait(&ret);
  34. return 0;
  35. }
结果:

in:3
out:3
文件描述符相同,说明每个进程都有自己的文件描述符表。

(4)、复制文件描述符

复制之前:


复制之后:



可以通过复制文件描述符实现输出重定向到文件,示例:

  1. #include <string.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <errno.h>
  5. #include <unistd.h>
  6. #define ERR_EXIT(m) \
  7. do \
  8. { \
  9. perror(m); \
  10. exit(EXIT_FAILURE); \
  11. }while(0)
  12. int main()
  13. {
  14. int fd;
  15. fd = open("aa.txt",O_WRONLY);
  16. if (fd == -1)
  17. ERR_EXIT("open error");
  18. close(1);
  19. dup(fd);//等价于dup2(fd,0);
  20. printf("Hello\n");
  21. return 0;
  22. }
结果"Hello"没有输出到屏幕,而是输出到文件,因为此时标准输出文件描述符1已经指向打开文件aa.txt。


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/235256
推荐阅读
相关标签
  

闽ICP备14008679号