1.实现能够随时收发,即AB可以 随时 互相收发消息:提示 用多线程 或者多线程
p1.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
char arr[64] = "";
int fp,fd;
pthread_t pth1,pth2;
void* callback1(void* arg)
{
while(1){
bzero(arr,sizeof(arr));
fgets(arr,sizeof(arr),stdin);
arr[strlen(arr)-1] = '\0';
write(fp,arr,strlen(arr));
if(strcmp(arr,"quit")==0)
{
break;
}
}
pthread_cancel(pth2);
return NULL;
}
void* callback2(void* arg)
{
while(1){
read(fd,arr,sizeof(arr));
if(strcmp(arr,"quit")==0)
{
break;
}
printf("p1.c从管道中读取:%s\n",arr);
bzero(arr,sizeof(arr));
}
pthread_cancel(pth1);
return NULL;
}
int main(int argc, const char *argv[])
{
if(mkfifo("./myfifo",0666)<0)
{
if(errno != 17)
{
perror("mkfifo");
return -1;
}
}
fp = open("./myfifo",O_RDWR);
if(fp<0)
{
perror("open");
return -1;
}
if(mkfifo("./youfifo",0666)<0)
{
if(errno != 17)
{
perror("youfifo");
return -1;
}
}
fd = open("./youfifo",O_RDWR);
if(fp<0)
{
perror("open");
return -1;
}
if(pthread_create(&pth1,NULL,callback1,NULL)!=0)
{
perror("1");
return -1;
}
if(pthread_create(&pth2,NULL,callback2,NULL)!=0)
{
perror("2");
return -1;
}
pthread_join(pth1,NULL);
pthread_join(pth2,NULL);
close(fp);
close(fd);
return 0;
}
1.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
char arr[64] = "";
int fp,fd;
pthread_t pth1,pth2;
void* callback1(void* arg)
{
while(1){
read(fp,arr,sizeof(arr));
if(strcmp(arr,"quit")==0)
{
break;
}
printf("1.c从管道中读取:%s\n",arr);
bzero(arr,sizeof(arr));
}
pthread_cancel(pth2);
return NULL;
}
void* callback2(void* arg)
{
while(1){
bzero(arr,sizeof(arr));
fgets(arr,sizeof(arr),stdin);
arr[strlen(arr)-1] = '\0';
write(fd,arr,strlen(arr));
if(strcmp(arr,"quit")==0)
{
break;
}
}
pthread_cancel(pth1);
return NULL;
}
int main(int argc, const char *argv[])
{
if(mkfifo("./myfifo",0666)<0)
{
if(errno != 17)
{
perror("mkfifo");
return -1;
}
}
fp = open("./myfifo",O_RDWR);
if(fp<0)
{
perror("open");
return -1;
}
if(mkfifo("./youfifo",0666)<0)
{
if(errno != 17)
{
perror("mkfifo");
return -1;
}
}
fd = open("./youfifo",O_RDWR);
if(fp<0)
{
perror("open");
return -1;
}
if(pthread_create(&pth1,NULL,callback1,NULL)!=0)
{
perror("1");
return -1;
}
if(pthread_create(&pth2,NULL,callback2,NULL)!=0)
{
perror("2");
return -1;
}
pthread_join(pth1,NULL);
pthread_join(pth2,NULL);
close(fp);
close(fd);
return 0;
}