![9499af5df79773e3228f17b52a798df2.png](https://i-blog.csdnimg.cn/blog_migrate/e0b935c3bea09b4913497e66f9049af8.png)
匿名管道,也称管道,是Linux下最常见的进程间通信方式之一。匿名管道在系统中没有实名,它只是进程的一种资源,会随着进程的结束而被系统清除。
管道的创建与关闭
Linux中使用pipe()函数创建一个匿名管道,其函数原型为:
#include <unistd.h>
int pipe(int fd[2]);
创建成功返回0,出错返回1。参数fd[2]是一个长度为2的文件描述符数组,fd[1]是写入端的文件描述符,fd[0]是读出端的文件描述符。
可以使用文件I/O函数read()和write()读管道进行读写,使用close()函数关闭管道两端。
示例,create_pipe.c:
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int fd[2];
char str[256];
if((pipe(fd))<0)
{
printf("create the pipe failed!n");
exit(1);
}
write(fd[1], "create the pipe sucessfully!n", 31);
read(fd[0], str, sizeof(str));
printf("%s", str);
printf("pipe file descriptors are%d,%dn", fd[0], fd[1]);
close(fd[0]);
close(fd[1]);
return 0;
}
编译后执行:
$ ./create_pipe
create t