Chinaunix首页 | 论坛 | 博客
  • 博客访问: 63245
  • 博文数量: 21
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 236
  • 用 户 组: 普通用户
  • 注册时间: 2014-09-05 21:34
文章分类

全部博文(21)

文章存档

2015年(21)

我的朋友

分类: LINUX

2015-08-05 20:06:55


点击(此处)折叠或打开

  1. //start from the very beginning,and to create greatness
  2. //@author: Chuangwei Lin
  3. //@E-mail:979951191@qq.com
  4. //@brief: 一个进程间管道通信的例子
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <unistd.h>
  9. #include <sys/types.h>
  10. int main(int argc, char const *argv[])
  11. {
  12.     int result = -1;//创建管道结果
  13.     int fd[2],nbytes;//文件描述符和字符个数
  14.     pid_t pid;//进程pid值
  15.     char string[] = "进程间管道通信";
  16.     char readbuffer[80];//字符缓冲区
  17.     //文件符1用于写,0用于读
  18.     int* write_fd = &fd[1];
  19.     int* read_fd = &fd[0];
  20.     result = pipe(fd);//建立管道
  21.     if(-1 == result)
  22.     {
  23.         printf("管道建立失败\n");
  24.         return -1;
  25.     }

  26.     pid = fork();//分叉进程
  27.     if (-1 == pid)
  28.     {
  29.         printf("fork进程失败\n");
  30.         return -1;
  31.     }
  32.     if (0 == pid)//子进程
  33.     {
  34.         close(*read_fd);//关闭读端
  35.         result = write(*write_fd,string,strlen(string));//向管道段写入字符
  36.         return 0;
  37.     }
  38.     else//父进程
  39.     {
  40.         close(*write_fd);//关闭写端

  41.         nbytes = read(*read_fd,readbuffer, sizeof(readbuffer));//从管道读数据
  42.         printf("接收到%d个数据,内容为:%s\n",nbytes,readbuffer);
  43.     }
  44.     return 0;
  45. }
运行结果为:
[root@localhost lcw20150805]# ./lcw_pipe
接收到21个数据,内容为:进程间管道通信
阅读(960) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~