读书人

UNIX:在爷儿俩进程间用管道技术通信

发布时间: 2013-01-23 10:44:50 作者: rapoo

UNIX:在父子进程间用管道技术通信

《Unix网络编程》这本书附带了许多短小精美的小程序,我在阅读此书的时候,将书上的代码按照自己的理解重写了一遍(大部分是抄书上的),加深一下自己的理解(纯看书太困了,呵呵)。此例子在Ubuntu10.04上测试通过。

PS:程序里使用了包裹函数(首字母是大写的函数)和常量(所有字母都是大写的常量)的声明在my_unp.h文件中,定义在unp_base.c和unp_thread.c中,地址:http://blog.csdn.net/aaa20090987/article/details/8096701

程序简介:这个程序演示了父子进程之间如果利用管道技术进行通信。


上代码:

[cpp] view plaincopyprint?
  1. #include "my_unp.h"
  2. void client(int readfd, int writefd)
  3. {
  4. size_t len;
  5. ssize_t n;
  6. char buff[MAXLINE];
  7. //从终端读入一行数据(文件路径)
  8. Fgets(buff, MAXLINE, stdin);
  9. len = strlen(buff);
  10. if( '\n' == buff[len-1] )
  11. len--;
  12. //将其写入管道
  13. Write(writefd, buff, len);
  14. //然后从管道中读出数据
  15. while( (n=Read(readfd, buff, MAXLINE)) > 0 )
  16. Write(STDOUT_FILENO, buff, n);
  17. }
  18. void server(int readfd, int writefd)
  19. {
  20. int fd;
  21. ssize_t n;
  22. char buff[MAXLINE];
  23. //从管道中读出一行数据(文件路经)
  24. if( (n=Read(readfd, buff, MAXLINE)) == 0 )
  25. error_quit("end of file while reading pathname");
  26. buff[n] = '\0';
  27. //打开文件
  28. fd = open(buff, O_RDONLY);
  29. //如果打开失败,就将失败原因写入管道
  30. if( fd < 0 )
  31. {
  32. snprintf(buff+n, sizeof(buff)-n, ": can't open, %s\n",
  33. strerror(errno));
  34. n = strlen(buff);
  35. Write(writefd, buff, n);
  36. }
  37. //否则,将文件内容写入管道
  38. else
  39. {
  40. while( (n=Read(fd, buff, MAXLINE)) > 0 )
  41. Write(writefd, buff, n);
  42. Close(fd);
  43. }
  44. }
  45. int main(int argc, char **argv)
  46. {
  47. int pipe1[2], pipe2[2];
  48. pid_t childpid;
  49. Pipe(pipe1);
  50. pipe(pipe2);
  51. childpid = Fork();
  52. //父子进程分别关闭自己不需要的管道端口
  53. if( childpid == 0 )
  54. {
  55. Close(pipe1[1]);
  56. Close(pipe2[0]);
  57. server(pipe1[0], pipe2[1]);
  58. }
  59. else
  60. {
  61. Close(pipe1[0]);
  62. Close(pipe2[1]);
  63. client(pipe2[0], pipe1[1]);
  64. //父进程必须等子进程退出之后才能退出
  65. Waitpid(childpid, NULL, 0);
  66. }
  67. return 0;
  68. }

运行示例(红色字体的为输入)

qch@ubuntu:~/code$gcc my_unp.c temp.c -o temp
#打开一个有两行字符串的文本文件
qch@ubuntu:~/code$./temp
text.txt
I'amChinese.
Hello,world.
#打开一个我们不能读的文件
qch@ubuntu:~/code$./temp
/etc/shadow
/etc/shadow:can't open, Permission denied
#打开一个不存在的文件
qch@ubuntu:~/code$ ./temp
aaaaa
aaaaa:can't open, No such file or directory

读书人网 >UNIXLINUX

热点推荐