pipe.txt

来自「进程管道通信」· 文本 代码 · 共 68 行

TXT
68
字号
#include<unistd.h>
int pipe(int filedis[2]);
#define INPUT 0
#define OUTPUT 1

int main()
{

int file_descriptors1[2];
int file_descriptors2[2];
int pid1,pid2;
char buf1[256];
int returned_count1,returned_count2;

pipe(file_descriptors1);
pipe(file_descriptors2);

pid1=fork();

if(pid1==-1){
printf("Error");
exit(1);
}


if(pid1==0){
printf("in the child1 process...\n"); 
close(file_descriptors1[INPUT]);
write(file_descriptors1[OUTPUT],"Child1 is sending a message",strlen("Child1 is sending a message"));
exit(0);
}

if(pid1>0){
wait(NULL);
printf("in the parent process...\n");
close(file_descriptors1[OUTPUT]);
returned_count1 = read(file_descriptors1[INPUT],buf1,sizeof(buf1));
printf("%d bytes of data received from spawned process:%s\n",returned_count1,buf1);


pid2=fork();

if(pid2==-1)
{
printf("Error");
exit(1);
}

if(pid2==0){
printf("in the child2 process...\n"); 
close(file_descriptors2[INPUT]);
write(file_descriptors2[OUTPUT],"Child2 is sending a message",strlen("Child2 is sending a message"));
exit(0);
}

if(pid2>0){
wait(NULL);
printf("in the parent process...\n");
close(file_descriptors2[OUTPUT]);
returned_count2 = read(file_descriptors2[INPUT],buf1,sizeof(buf1));
printf("%d bytes of data received from spawned process:%s\n",returned_count2,buf1);
}

}
return(0);

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?