码迷,mamicode.com
首页 > 系统相关 > 详细

进程间管道通信

时间:2017-07-18 12:04:16      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:进程通信

父子进程间通过管道通信。

管道只能在具有公共祖先的两个进程间使用,通常,一个管道有另一个进程创建,在进程调用fork之后,这个管道就能在父进程和子进程之间使用了。


一般的进程,fd[0]表示读,fd[1]表示写。

技术分享

如果有用到管道,则写进管道,从管道读。

技术分享

父子进程之间。

技术分享

所以,通过简单的read ,write函数,把目标文件设为fd[0] fd[1]即可以完成父子进程间的通信。

write用法,read类似。  
  int write(int handle, void *buf, int nbyte); 
  handle 是 文件描述符; 
  buf是指定的缓冲区,即 指针,指向一段内存单元; 
  nbyte是要写入 文件指定的字节数;返回值:写入文档的字节数(成功);-1(出错) 
  write函数把buf中nbyte写入文件描述符handle所指的文档,成功时返回写的字节数,错误时返回-1. 

#include<unistd.h>

#include<stdio.h>

#include<stdlib.h>

#define BUFSZ 256


int main(void)

{

        int fd[2];

        char buf[BUFSZ];

        pid_t pid;

        int len;

        if( pipe(fd)<0 )

        {

                perror("failed to pipe");

                exit(1);

        }

        if( (pid = fork())<0 )

        {

                perror("failed to fork");

                exit(1);

        }

    else if(pid > 0)


  {

                printf("father wrote password to pipe\n");

                write(fd[1], "1234\n", 25);             父进程把password写进后sleep,等待子进程来读取。

            sleep(1);

             read(fd[0], buf, BUFSZ);

            printf("father read result is %s\n", buf);

                exit(0);

        }

        else

        {

                printf("child will read from pipe\n");

                read(fd[0], buf, BUFSZ);                                         子进程从管道中读取父进程写进的password

                printf("child read result is %s\n", buf);

            printf("child wrote password to pipe\n");

            write(fd[1], "4321\n", 25);                                   子进程把自己的password写进,等待父进程读取

        }

                return 0;

}


运行结果如下:

[root@localhost xcui]# ./pipe

father wrote password to pipe

child will read from pipe

child read result is 1234


child wrote password to pipe

father read result is 4321


进程间管道通信

标签:进程通信

原文地址:http://12833256.blog.51cto.com/12823256/1948464

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!