1.创建AB进程,实现AB进程的通话。
1)A进程先发送一句话给B进程,B进程接收打印。
2)B进程发送与句话给A进程,A进程接收后打印。
3)重复1)2)步骤即可。
4)当A进程或者B进程发送quit后,AB进程均要结束
将上述练习修改成:AB进程能够随时收发形式
提示:用多线程,多进程,
进程A
#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
void * callback1(void* p)
{
while(1)
{
char arr[128]="";
fgets(arr,128,stdin);
arr[strlen(arr)-1]='\0';
write(*(int *)p,arr,128);
}
}
void * callback2(void *p)
{
while(1)
{
char brr[128]="";
read(*(int*)p,brr,128);
printf("%s\n",brr);
}
}
int main(int argc, const char *argv[])
{
if (mkfifo("fifo_1",0777)<0)
{
if(errno!=17)
{
perror("mkfifo1");
return -1;
}
}
if (mkfifo("fifo_2",0777)<0)
{
if(errno!=17)
{
perror("mkfifo2");
return -1;
}
}
int fd_1=open("fifo_1",O_RDWR);
if (fd_1<0)
{
perror("open1");
return -1;
}
int fd_2=open("fifo_2",O_RDWR);
if (fd_2<0)
{
perror("open2");
return -1;
}
pthread_t pt_1;
int p_1=pthread_create(&pt_1,NULL,callback1,&fd_1);
if (p_1!=0)
{
perror("pthread_create");
return -1;
}
pthread_t pt_2;
int p_2=pthread_create(&pt_2,NULL,callback2,&fd_2);
if (p_2!=0)
{
perror("pthread_create");
return -1;
}
pthread_join(pt_1,NULL);
pthread_join(pt_2,NULL);
return 0;
}
进程B
#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
void * callback1(void* p)
{
while(1)
{
char arr[128]="";
fgets(arr,128,stdin);
arr[strlen(arr)-1]='\0';
write(*(int *)p,arr,128);
}
}
void * callback2(void *p)
{
while(1)
{
char brr[128]="";
read(*(int*)p,brr,128);
printf("%s\n",brr);
}
}
int main(int argc, const char *argv[])
{
if (mkfifo("fifo_1",0777)<0)
{
if(errno!=17)
{
perror("mkfifo1");
return -1;
}
}
if (mkfifo("fifo_2",0777)<0)
{
if (errno!=17)
{
perror("mkfifo2");
return -1;
}
}
int fd_1=open("fifo_1",O_RDWR);
if (fd_1<0)
{
perror("open1");
return -1;
}
int fd_2=open("fifo_2",O_RDWR);
if (fd_2<0)
{
perror("open2");
return -1;
}
pthread_t pt_1;
int p_1=pthread_create(&pt_1,NULL,callback1,&fd_2);
if (p_1!=0)
{
perror("pthread_create");
return -1;
}
pthread_t pt_2;
int p_2=pthread_create(&pt_2,NULL,callback2,&fd_1);
if (p_2!=0)
{
perror("pthread_create");
return -1;
}
pthread_join(pt_1,NULL);
pthread_join(pt_2,NULL);
return 0;
}