匿名管道通讯
作者:互联网
父子进程匿名管道通讯
示例:pipe.c(子读父写)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#define BUFFSIZE 1024
int main()
{
int pfd[2];
pid_t pid;
char buff[BUFFSIZE];
if(pipe(pfd) < 0) //创建匿名管道
{
perror("pipe()");
exit(1);
}
pid = fork(); //创建子进程
if(pid<0)
{
perror("fork()");
exit(1);
}
if(pid ==0) //子进程
{
close(pfd[1]); //关闭写文件
memset(buff,0,BUFFSIZE);
read(pfd[0],buff,BUFFSIZE);
puts(buff);
close(pfd[0]); //读完关闭读文件
}
else //父进程
{
close(pfd[0]); //关闭读文件
write(pfd[1],"hello",5);
close(pfd[1]); /写完关闭写文件
wait(NULL); //等待子进程结束
}
exit(0);
}
标签:通讯,pfd,BUFFSIZE,pid,管道,匿名,close,include,buff 来源: https://www.cnblogs.com/linux-learn/p/16545747.html