管道-两个子进程写父进程读.txt
来自「这是linux下关于进程操作的两个例子,分别是"父子进程都写入文件"和"管道-两」· 文本 代码 · 共 54 行
TXT
54 行
/*编写一个程序,建立一个管道,父进程生成子进程X,Y,分别写入管道,父进程读*/
#include<unistd.h>
#include<sys/types.h>
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<string.h>
#include<errno.h>
int main(void)
{
static const char mesg1[]="这是子进程#1#写的";
static const char mesg2[]="这是子进#2#写的";
int x,y,fd[2];
char buf[100];
size_t n1,n2,n;
n1=strlen(mesg1);
n2=strlen(mesg2);
n=n1+n2;
pipe(fd);
while((x=fork())==-1);
if(x==0)
{
printf("进入子进程1\n");
if(write(fd[1],mesg1,n1)!=n1)
{perror("进程一写");exit(1);}
else
{printf("进程一写成功\n");exit(0);}
}
else
{printf("进入父进程了\n");
while((y=fork())==-1);
if(y==0)
{ printf("进入进程2\n");
if(write(fd[1],mesg2,n2)!=n2)
{perror("进程二写");exit(1);}
else
{printf("进程二写成功\n");exit(0);}
}
else
{
if(read(fd[0],buf,100)!=n)
{perror("父进程读");exit(1);}
else
{printf("以下是父进程读的内容:\n");
buf[n]='\0';
printf("%s",buf);
printf("\n");
close(fd[0]);
close(fd[1]);
exit(0);
}
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?