1:实现2个终端之间的互相聊天
要求:千万不要做出来2个终端之间的消息发送是读一写的,一定要能够做到,一个终端发送n条消息,另一个终端一条消息都不回复都是没有问题的
终端A:
#include<myhead.h>
int main(int argc, char *argv[])
{int var=fork();if(var>0){char afifo[32]="./afifo";int res=access(afifo,F_OK);if(res==-1){mkfifo(afifo,0666);}int afd=open(afifo,O_WRONLY|O_TRUNC);char abuf[128]={0};int alen=0;while(1){memset(abuf,0,alen);scanf("%128s",abuf);while(getchar()!=10);alen=strlen(abuf);write(afd,abuf,alen);}close(afd);}else if(var==0){ char bfifo[32]="./bfifo";if(access(bfifo,F_OK)==-1){mkfifo(bfifo,0666);}int bfd=open(bfifo,O_RDONLY);char bbuf[128]={0};int blen=0;while(1){memset(bbuf,0,blen);blen=read(bfd,bbuf,128);printf("B:%s\n",bbuf);}close(bfd);}else if(var<0){perror("fork");return 1;}return 0;
}
ubuntu@ub
终端B:
#include<myhead.h>
int main(int argc, char *argv[])
{int var=fork();if(var>0){char afifo[32]="./afifo";if(access(afifo,F_OK)==-1){mkfifo(afifo,0666);}int afd=open(afifo,O_RDONLY);char abuf[128]={0};int alen=0;while(1){memset(abuf,0,alen);alen=read(afd,abuf,128);printf("A:%s\n",abuf);}close(afd);}else if(var==0){char bfifo[32]="./bfifo";int res=access(bfifo,F_OK);if(res==-1){mkfifo(bfifo,0666);}int bfd=open(bfifo,O_WRONLY|O_TRUNC);char bbuf[128]={0};int blen=0;while(1){memset(bbuf,0,blen);scanf("%128s",bbuf);while(getchar()!=10);blen=strlen(bbuf);write(bfd,bbuf,blen);}close(bfd);}else if(var==-1){perror("fork");return 1;}return 0;
}
效果图:
2:有2个.c文件1.c,2.c
1.c的代码负责:从键盘输入三角形的三边长 或者 长方形的长和宽
2.c的代码负责:根据1.c 输入的数据,计算三角形 或者 长方形的面积
1.c:
#include<myhead.h>
int main(int argc, char *argv[])
{int pipefd[2]={0};pipe(pipefd);//pipefd[0]=3//pipefd[1]=4;int res=fork();if(res>0){while(1){double data[3]={0};printf("请输入三角形的三边长或者长方形的长和宽:");scanf("%lf %lf %lf",data,data+1,data+2);while(getchar()!=10);write(pipefd[1],data,24);sleep(1);}}else if(res==0){char rfd[4]={0};sprintf(rfd,"%d",pipefd[0]);execl("./2","2",rfd,NULL);perror("execl");}return 0;
}
2.c:
#include<myhead.h>
int main(int argc, char *argv[])
{double buf[3]={0};double area=0;int rfd=atoi(argv[1]);while(1){read(rfd,buf,24);if(buf[0]!=0&&buf[1]!=0&&buf[2]!=0){double a=buf[0];double b=buf[1];double c=buf[2];double p=(a+b+c)/2;double q=p*(p-a)*(p-b)*(p-c);area=sqrt(q);printf("三角形面积为:%f\n",area);}else if(buf[0]==0){area=buf[1]*buf[2];printf("长方形面积为:%f\n",area);}else if(buf[1]==0){area=buf[0]*buf[2];printf("长方形面积为:%f\n",area);}else if(buf[2]==0){area=buf[1]*buf[0];printf("长方形面积为:%f\n",area);}}return 0;
}
效果图:
思维导图: