用于亲缘间进程通信;
有固定的读端和写端;
不会在磁盘系统中存在,是临时文件。
函数:pipe
pipe.c
/*===============================================
* 文件名称:pipe.c
* 创 建 者:cxy
* 创建日期:2024年02月06日
* 描 述:
================================================*/
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
int main()
{
int pipefd[2] = {0}; //pipefd[0]为read端 pipefd[1]为write端
pipe(pipefd); //创建无名管道,并获得读、写端
pid_t pid = fork(); //创建子进程
if(0 == pid) //子进程
{
char buf[30] = {0};
int len;
while(1)
{
fgets(buf,sizeof(buf),stdin); //会获取空格、换行符
len = strlen(buf); //字符串有效长度包括换行符
if(buf[len-1] == '\n')
buf[len-1] = '\0'; //将换行符换为字符串结束标志'\0'
write(pipefd[1],buf,strlen(buf)); //buf中数据从写端写入无名管道
}
}
else //父进程
{
char buf[30] = {0};
while(1)
{
read(pipefd[0],buf,sizeof(buf)); //无名管道读端读取数据到buf
printf("buf:%s\n",buf); //打印
memset(buf,0,sizeof(buf)); //清空buf
}
}
return 0;
}
结果

本文详细介绍了如何使用C语言中的`pipe()`函数创建无名管道,并展示了父子进程如何通过读端和写端进行通信,父进程从标准输入读取数据并通过管道传递给子进程。
82

被折叠的 条评论
为什么被折叠?



