#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//管道通讯:单向,先进先出,管道尾部写入数据,管道头部读出数据;数据读出后,管道将自动删除该数据;
//无名管道,用于父子进程间通讯,先创建管道,再fork创建子进程,该子进程继承父进程创建的管道;
// 管道创建 int pipe(int filedis[2]); 管道关闭close(filedis[2]);
int main()
{
int pipe_fd[2];
pid_t pid;
char buf[100];
int readnum,writenum;
memset(buf,0,100);//清buf
if(pipe(pipe_fd)<0)
{
printf("creat pipe failure!\n");
exit(1);
}
else
printf("creat pipe success!\n");
if((pid=fork())==0)//子进程
{
close(pipe_fd[1]);//关闭管道尾部(管道写)
if((readnum=read(pipe_fd[0],&buf,6))>0)
printf("read pipe success,number=%d,data=%s\n",readnum,buf);
else if(readnum==0)
printf("pipe is empty!\n");
else
printf("read pipe failure!\n");
if((readnum=read(pipe_fd[0],&buf,15))>0)
printf("read pipe success,number=%d,data=%s\n",readnum,buf);
else if(readnum==0)
printf("pipe is empty!\n");
else
printf("read pipe failure!\n");
close(pipe_fd[0]);//关闭管道头部,管道读结束
exit(0);
}
else if(pid>0)
{
close(pipe_fd[0]);//关闭管道头部(管道读)
if((writenum=write(pipe_fd[1],"delta electronic ",17))>0)
printf("write pipe success!,number=%d,data=%s\n",writenum,"delta electronic ");
else
printf("write pipe failure!\n");
if((writenum=write(pipe_fd[1],"will",4))>0)
printf("write pipe success!,number=%d,data=%s\n",writenum,"will");
else
printf("write pipe failure!\n");
close(pipe_fd[1]);//关闭管道尾部,管道写结束
waitpid(pid,NULL,0);//等待子进程结束
exit(0);
}
exit(0);
}
linux 管道
最新推荐文章于 2024-03-14 16:16:02 发布