Chinaunix首页 | 论坛 | 博客
  • 博客访问: 238187
  • 博文数量: 35
  • 博客积分: 791
  • 博客等级: 军士长
  • 技术积分: 510
  • 用 户 组: 普通用户
  • 注册时间: 2012-09-05 16:56
文章分类
文章存档

2013年(7)

2012年(28)

我的朋友

分类: 嵌入式

2012-09-05 17:51:47

程序要求:

     子进程读,父进程写,由pipe管道来实现进程间的通信

程序如下:


点击(此处)折叠或打开

  1. #include <stdio.h>
  2.     #include <stdlib.h>
  3.     #include <string.h>
  4.     #include <unistd.h>
  5.       
  6.     static void child_read(int *);
  7.     static void father_write(int *, int );
  8.       
  9.     int main(int argc, const char *argv[])
  10.     {
  11.         pid_t pid;
  12.         int pipe_fd[2];
  13.       
  14.         if (pipe(pipe_fd) < 0) //创建pipe管道
  15.         {
  16.             perror("failed to create pipe");
  17.             exit(-1);
  18.         }
  19.       
  20.         if ((pid = fork()) < 0)
  21.         {
  22.             perror("failed to fork pid");
  23.             exit(-1);
  24.         }
  25.       
  26.         if (pid == 0)
  27.             child_read(pipe_fd); //子进程负责读数据
  28.         else
  29.             father_write(pipe_fd, pid); //父进程负责写数据
  30.       
  31.         return 0;
  32.     }
  33.       
  34.     static void child_read(int *pipe_fd)
  35.     {
  36.         char buf[100];
  37.       
  38.         close(pipe_fd[1]); //子进程负责读数据,因此关闭写端
  39.       
  40.         while (read(pipe_fd[0], buf, sizeof(buf)) > 0) //读数据
  41.          {
  42.             if (strncmp(buf, "quit", 4) == 0)
  43.                 exit(0);
  44.       
  45.             printf("read : %s\n", buf);
  46.             memset(buf, sizeof(buf), 0);
  47.         }
  48.       
  49.         return ;
  50.     }
  51.       
  52.     static void father_write(int *pipe_fd, int pid)
  53.     {
  54.         char buf[100];
  55.       
  56.         close(pipe_fd[0]); //同理,关闭读端
  57.       
  58.         while (1)
  59.         {
  60.             usleep(500);
  61.             printf(">");
  62.             fgets(buf, sizeof(buf), stdin);
  63.             buf[strlen(buf) - 1] = 0;
  64.       
  65.             write(pipe_fd[1], buf, strlen(buf) + 1); //写数据
  66.       
  67.             if (strncmp(buf, "quit", 4) == 0)
  68.                 break;
  69.                   
  70.             memset(buf, sizeof(buf), 0);
  71.         }
  72.       
  73.         waitpid(pid, NULL, 0);
  74.       
  75.         return ;
  76.     }

阅读(1888) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~