Linux下的管道通信

来源:互联网 发布:mysql5.7数据库下载 编辑:程序博客网 时间:2024/06/01 09:23

管道通信方式分为无名管道和又名管道,无名管道可用于具有亲缘关系的进程间,有名管道可以没有亲缘关系的进程通信。

1)管道是半双工的,数据只能向一个方向移动,所以,需要两个进程互相通信时需要建立两个管道。

2)数据的读出和写入:一个进程向管道中写的内容被管道另一端的进程读出。写入的内容每次都添加在管道缓冲区的末尾,并且每次都是从缓冲区的头部读出数据。

3)它是一个之存在与内存的特殊文件,并且数据只能单向流动,而且只能用于具有亲缘关系的进程间(即父子进程,兄弟进程),无亲缘关系的进程是不能使用的。如果要使用管道进行全双工通信,那么就要建立两个管道,通过管道通信的两个进程,一个进程向管道写数据,而另一个进程从管道读数据。

一、创建无名管道

pipe函数


头文件:  #include <unistd.h>

函数原型:int pipe(int field[2]);

函数说明:pipe会建立管道,并且将文件描述符由参数field数组返回,field[0]为管道的读取端,field[1]为管道的写入端

返回值:成功:0    出错:-1;


例如:


/*父进程借管道将字符串hello!\n传给子进程并显示*/#include <unistd.h>int main(){    int filedes[2];    char buffer[80];    pipe(filedes[2]);    if(fork()>0)    {        char s[] = "hello\n";        write(filedes[1],s,sizeof(s));    }    else    {        read(filedes[0],buffer,80);        printf("%s",buffer);    }}

从管到中读数据:

1)如果管道的写端不存在,则认为已经读到数据的末尾,读函数返回的读出字节数为0,。


#include <unistd.h>#include <sys/types.h>#include <errno.h>#include <stdio.h>#include <stdlib.h>int main(){int pipe_fd[2];pid_t pid;char buf_r[100];char* p_wbuf;int r_num;memset(buf_r,0,sizeof(buf_r));/*创建管道*/if(pipe(pipe_fd)<0){printf("pipe create error\n");return -1;}/*创建子进程*/if((pid=fork())==0)  //子进程 {printf("\n");close(pipe_fd[1]);sleep(2); /*为什么要睡眠*/if((r_num=read(pipe_fd[0],buf_r,100))>0){printf(   "%d numbers read from the pipe is %s\n",r_num,buf_r);}close(pipe_fd[0]);exit(0);  }else if(pid>0){close(pipe_fd[0]);if(write(pipe_fd[1],"Hello",5)!=-1)printf("parent write1 Hello!\n");if(write(pipe_fd[1]," Pipe",5)!=-1)printf("parent write2 Pipe!\n");close(pipe_fd[1]);sleep(3);waitpid(pid,NULL,0); /*等待子进程结束*/exit(0);}return 0;}





0 0
原创粉丝点击