利用匿名管道實作兄弟程序間通信,要求
1.兄程序發送字元串“This is elder brother ,pid is (兄程序程序号)”給弟程序;
2.弟程序收到兄程序發送的資料後,給兄程序回複“This is younger brother ,pid is(第程序程序号)”;
源代碼:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char *argv[])
{
char str1[50],num1[50],str2[50],num2[50];
int fd1[2],fd2[2];//0用于讀,1用于寫
pipe(fd1);
pipe(fd2);
int pid=fork();
if(pid==0)
{
close(fd1[0]);
close(fd2[1]);
//char str[50],num[10];
strcpy(str1,"This is elder brother,pid is ");
sprintf(num1,"%d",getpid());
strcat(str1,num1);
write(fd1[1],str1,50);
read(fd2[0],str2,50);
printf("\n%s\n",str2);
}
else if(pid>0)
{
int n=fork();
if(n==0)
{
close(fd1[1]);
close(fd2[0]);
//char str[50],num[10];
read(fd1[0],str1,50);
printf("\n%s\n",str1);
strcpy(str2,"This is younger brother,pid is ");
sprintf(num2,"%d",getpid());
strcat(str2,num2);
write(fd2[1],str2,50);
}
else if (n>0)
{
close(fd1[0]);
close(fd2[1]);
close(fd2[0]);
close(fd1[1]); }
}
else
{
perror("fork error;");
}
return 0;
}
匿名管道相關函數請參考:點選打開連結
https://blog.csdn.net/qq_37192076/article/details/80456769