创建AB进程,实现AB进程的通话。
AB进程能够随时收发形式
当A进程或者B进程发送quit后,AB进程均要结束。
term1.c
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
char qstr[]="quit\n";
void *rptcell(void *arg)
{
char rstr[100];
int fr = open("term2massage",O_RDWR);
while(1){
bzero(rstr,100);
read(fr,rstr,100);
if(!strcmp(rstr,qstr)){
exit(0);
}
printf("\rtermal2\n%s\t\t\n\n",rstr);
printf("termal1:");
fflush(stdout);
}
}
int main(int argc, const char *argv[])
{
char str[100];
pthread_t rpt;
if(mkfifo("term1massage",0777)==-1){
if(errno!=17){
perror("term1massage:");
return -1;
}
}
if(mkfifo("term2massage",0777)==-1){
if(errno!=17){
perror("term2massage:");
return -1;
}
}
if(pthread_create(&rpt,NULL,rptcell,NULL)){
perror("pthread_create:");
return -1;
}
int fw = open("term1massage",O_RDWR);
while(1){
bzero(str,100);
printf("\rtermal1:");
fflush(stdout);
fgets(str,100,stdin);
printf("\rtermal1:\n%s\t\t\n\n",str);
fflush(stdin);
write(fw,str,100);
if(!strcmp(str,qstr)){
exit(0);
}
}
return 0;
}
term2.c
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
char qstr[]="quit\n";
void *rptcell(void *arg)
{
char rstr[100];
int fr = open("term1massage",O_RDWR);
while(1){
bzero(rstr,100);
read(fr,rstr,100);
if(!strcmp(rstr,qstr)){
exit(0);
}
printf("\rtermal1:\n%s\t\t\n\n",rstr);
printf("termal2:");
fflush(stdout);
}
}
int main(int argc, const char *argv[])
{
char str[100];
pthread_t rpt;
if(mkfifo("term1massage",0777)==-1){
if(errno!=17){
perror("term1massage:");
return -1;
}
}
if(mkfifo("term2massage",0777)==-1){
if(errno!=17){
perror("term2massage:");
return -1;
}
}
if(pthread_create(&rpt,NULL,rptcell,NULL)){
perror("pthread_create:");
return -1;
}
int fw = open("term2massage",O_RDWR);
while(1){
bzero(str,100);
printf("\rtermal2:");
fflush(stdout);
fgets(str,100,stdin);
printf("\rtermal2:\n%s\t\t\n\n",str);
fflush(stdin);
write(fw,str,100);
if(!strcmp(str,qstr)){
exit(1);
}
}
return 0;
}