📄 fatherandchildpipe.c
字号:
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <limits.h>
int main()
{
int pipe_fd1[2],pipe_fd2[2],pipe_fd3[2],pipe_fd4[2];
pid_t child1,child2,child3,child4;
char buf_r1[100],buf_r2[100],buf_r3[100],buf_r4[100];
char *p_wbuf;
int r_num;
char s[100];
int len;
int i;
//memset(buf_r1,0,sizeof(buf_r1));
// memset(buf_r2,0,sizeof(buf_r2));
// memset(buf_r3,0,sizeof(buf_r3));
// memset(buf_r4,0,sizeof(buf_r4));
if(pipe(pipe_fd1)<0)
{
printf("creat pipe error");
return -1;
}
if(pipe(pipe_fd2)<0)
{
printf("creat pipe error");
return -1;
}
if(pipe(pipe_fd3)<0)
{
printf("creat pipe error");
return -1;
}
if(pipe(pipe_fd4)<0)
{
printf("creat pipe error");
return -1;
}
if((child1=fork())==0)
{
close(pipe_fd1[1]);
sleep(2);
while((r_num=read(pipe_fd1[0],buf_r1,PIPE_BUF-1))>0)
{
printf("child1 %d numbers read from pipe is %s\n",r_num,buf_r1);
}
}
else if((child2=fork())==0)
{
close(pipe_fd2[1]);
sleep(2);
while((r_num=read(pipe_fd2[0],buf_r2,PIPE_BUF-1))>0)
{
printf("child2 %d numbers read from pipe is %s\n",r_num,buf_r2);
}
}
else if((child3=fork())==0)
{
close(pipe_fd3[1]);
sleep(2);
while((r_num=read(pipe_fd3[0],buf_r3,PIPE_BUF-1))>0)
{
printf("child3 %d numbers read from pipe is %s\n",r_num,buf_r3);
}
}
else if((child4=fork())==0)
{
close(pipe_fd4[1]);
sleep(2);
while((r_num=read(pipe_fd4[0],buf_r4,PIPE_BUF-1))>0)
{
printf("child4 %d numbers read from pipe is %s\n",r_num,buf_r4);
}
}
else
{
close(pipe_fd1[0]);
close(pipe_fd2[0]);
close(pipe_fd3[0]);
close(pipe_fd4[0]);
while(1)
{
printf("please input data\n");
scanf("%s",s);
// printf("data is %s\n",s);
len=strlen(s);
// printf("data len is %d\n",len);
if(write(pipe_fd1[1],s,len)!=-1)
{
printf("write data to pipe success\n");
}
if(write(pipe_fd2[1],s,len)!=-1)
{
printf("write data to pipe success\n");
}
if(write(pipe_fd3[1],s,len)!=-1)
{
printf("write data to pipe success\n");
}
if(write(pipe_fd4[1],s,len)!=-1)
{
printf("write data to pipe success\n");
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -