5.编写程序实现以下功能:
利用匿名管道实现兄弟进程间通信,要求
兄进程发送字符串“This is elder brother ,pid is (兄进程进程号)”给第进程;
第进程收到兄进程发送的数据后,给兄进程回复“This is younger brother ,pid is(第进程进程号)”。
代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#define size 256
int main()
{
int fd[2],fds[2];
char buf[size];
pid_t pid;
if(pipe(fd)<0)
{
perror("pipe:");
exit(1);
}
if(pipe(fds)<0)
{
perror("pipe:");
exit(1);
}
if((pid=fork())<0)
{
perror("failed to fork");
exit(1);
}
else if(pid==0)
{
//char str[50]="This is younger brother,pis is:";
char str[50];
strcpy(str,"This is younger brother,pis is");
char ids[50];
sprintf(ids,"%d",getpid());
strcat(str,ids);
close(fd[1]);
close (fds[0]);
write(fds[1],str,50);
read(fd[0],buf,size);
printf("%s\n",buf);
exit(0);
}
else if(pid>0)
{
int pids;
if((pids=fork())<0)
{
perror("pids fork:");
exit(1);
}
else if(pids==0)
{
//char str[50]="This is elder brother,pid is:";
char str[50];
char strs[50];
strcpy(str,"This is elder brother,pid is:");
char ids[50];
sprintf(ids,"%d",getpid());
strcat(str,ids);
printf("%s\n",str);
close(fd[0]);
close (fds[1]);
read(fds[0],strs,50);
write(fd[1],str,50);
exit(0);
}
else
exit(0);
}
return 0;
}