linux 匿名管道实例详解

linux中进程的一种通信方式——匿名管道

pipe函数建立管道

调用pipe函数时在内核中开辟一块缓冲区(称为管道)用于通信,它有一个读端一个写端,然后通过_pipe参数传出给用户程序两个文件描述符,_pipe[0]指向管道的读端,_pipe[1]指向管道的写端。所以管道在用户程序看起来就像一个打开的文件,通过read(_pipe[0]);或者write(_pipe[1]);向这个文件读写数据其实是在读写内核缓冲区。pipe函数调用成功返回0,调用失败返回-1。

1父进程调用pipe开辟管道,得到两个文件描述符指向管道的两端。

2. 父进程调用fork创建⼦进程,那么子进程也有两个文件描述符指向同一管道。

3. 父进程关闭管道读端,子进程关闭管道写端。父进程可以往管道里写,子进程可以从管道⾥读,管道是用环形队列实现的,数据从写端流入从读端流出,这样就实现了进程间通信

匿名管道间的通信是单向的,并且是、只能是具有血缘关系的进程间通信

#include<stdio.h> #include<unistd.h> #include<string.h> #include<stdlib.h>  int main() {   int _pipe[2];   int ret = pipe(_pipe);   if (ret < 0)   {     perror("pipe");     return 1;   }   pid_t id = fork ();   if (id<0)   {     perror("fork");     return 2;   }   else if (id == 0)   {     // child     int count =5;     close (_pipe[0]);     char* msg = "hello bit";     while (count --)     {       write(_pipe[1],msg,strlen(msg));       sleep(1);     }     close (_pipe[1]);     exit(123);   }   else    {     // Father     close(_pipe[1]);     char buf[128];     while(1)     {       int count =5;       ssize_t s = read ( _pipe[0],buf,sizeof(buf)-1);       if (s<0)       {         perror("read");       }       else if(s==0)       {         printf("write is close\n");         return 2;       }       else       {         buf[s] ='\0';         printf ("child >> father: %s\n",buf);       }       count --;       if (count == 0)       {         close (_pipe[0]);         break;       }     }          int status = 0;     pid_t _wait = waitpid (id, &status,0);     if (_wait > 0)     {       printf("exit code is %d, signal is %d\n",           WIFEXITED(status), status & 0xff);     }      }        return 0; } 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

思想如钻子,必须集中在一点钻下去才有力量

linux 匿名管道实例详解

相关文章:

你感兴趣的文章:

标签云: