歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux管道的一些細節

Linux管道的一些細節

日期:2017/3/1 11:16:06   编辑:Linux編程

讀管道:

1、進程從管道中讀取數據時,進程被掛起直到數據被寫進管道。(如果管道被兩個進程共享,進程A關閉了讀端,進程B讀寫都開啟,B使用讀端時,會一直等待B進程的寫端的動作,而不會理會A的動作。)

2、當所有的寫者關閉了管道的寫數據端時,試圖從管道中讀取數據的調用返回0,意味著文件結束。

3、管道是一個隊列。一個進程從管道中讀取數據後,數據已經不存在了。如果兩個進程都試圖對同一個管道進行度操作,在一個讀取一些之後,另一個進程讀到的將是後面的內容。他們讀到的數據必然是不完整的,除非兩個進程用某種方式來協調它們對管道的訪問。

寫管道:

1、管道容納的數據量是有限的,比磁盤文件差很多。如果進程想寫入1000個字節,而管道只能容納500個,那麼寫入調用只能等待,直到管道中再有500個字節。

2、當所有讀者都關閉讀數據端,則寫操作失敗。首先內核發送SIGPIPE消息給進程。若進程被終止,則無任何事情發生,否則write調用返回-1,並且將errno置為EPIPE。

3、POSIX標准規定內核不會拆分小於512字節的塊。而Linux則保證管道中可以存在4096字節的連續緩存。如果兩個進程向管道寫數據,並且每一個進程都限制其消息不大於512字節,那麼這些消息都不會被內核拆分。

這個示例程序,簡單地展示了管道的使用:

  1. /*
  2. * @FileName: pipedemo.c
  3. * @Author: wzj
  4. * @Brief:
  5. *
  6. * @History:
  7. *
  8. *
  9. *
  10. * @Date: 2011年10月04日星期二18:55:23
  11. *
  12. */
  13. #include<stdio.h>
  14. #include<unistd.h>
  15. #include<stdlib.h>
  16. #include<string.h>
  17. #include<fcntl.h>
  18. int main()
  19. {
  20. int len, i, apipe[2];
  21. char buf[BUFSIZ];
  22. int tmfd;
  23. // tmfd = open("/etc/passwd", O_RDONLY);
  24. // dup2(tmfd, 2); // redirect output...
  25. // close(tmfd);
  26. // close(0); // can't get the input...
  27. // close(1); // can't output...
  28. close(2);
  29. /*get a pipe*/
  30. if(pipe(apipe) == -1)
  31. {
  32. perror("could not make pipe");
  33. exit(1);
  34. }
  35. printf("Got a pipe ! It is file descriptors: \
  36. { %d %d} BUFSIZE:%d\n", apipe[0], apipe[1], BUFSIZ);
  37. /*read from stdin, write into pipe, read from pipe, print*/
  38. while(fgets(buf, BUFSIZ, stdin))
  39. {
  40. len = strlen(buf);
  41. if(write(apipe[1], buf, len) != len)
  42. {
  43. perror("writing to pipe");
  44. break;
  45. }
  46. for(i=0; i<len ; i++)
  47. {
  48. buf[i] = 'X';
  49. }
  50. len = read(apipe[0], buf, BUFSIZ);
  51. if(len == -1)
  52. {
  53. perror("reading from pipe");
  54. break;
  55. }
  56. if(write(1, buf, len) != len)
  57. {
  58. perror("writing to stdout");
  59. break;
  60. }
  61. }
  62. return 0;
  63. }
Copyright © Linux教程網 All Rights Reserved