双人聊天室:
#include <myhead.h>
//子线程1用于向管道1写入数据
void* WRITE(void* arg)
{
int fd1;
if((fd1=open("./fifo1",O_WRONLY|O_CREAT|O_TRUNC,0664))==-1)
{
perror("");
}
while(1)
{
char buf[128];
fgets(buf,sizeof(buf),stdin);//从终端输入中读取数据
//判断用户输入,输入q退出输入
if(!strcmp(buf,"bye"))
{
break;
}
buf[strlen(buf)-1] = '\0';
write(fd1,buf,strlen(buf));//将数据写入管道文件
}
close(fd1);
pthread_exit(NULL);
}
//子线程2用于读取管道2中的数据
void* READ(void* arg)
{
//打开两个管道文件
int fd2;
if((fd2=open("./fifo2",O_RDONLY))==-1)
{
perror("");
}
while(1)
{
char buf[128]="";
read(fd2,buf,sizeof(buf));
if(!strcmp(buf,"bye"))
{
break;
}
printf("她对我说:%s\n",buf);
}
close(fd2);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//创建两个子线程
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,WRITE,NULL)==-1)
{
perror("");
return -1;
}
if(pthread_create(&tid2,NULL,READ,NULL)==-1)
{
perror("");
return -1;
}
//回收子线程
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
```c
#include <myhead.h>
//子线程1用于向管道2写入数据
void* WRITE(void* arg)
{
int fd2 = *(int *)arg;
while(1)
{
char buf[128];
fgets(buf,sizeof(buf),stdin);//从终端输入中读取数据
//判断用户输入,输入q退出输入
if(!strcmp(buf,"bye"))
{
break;
}
buf[strlen(buf)-1] = '\0';
write(fd2,buf,strlen(buf));//将数据写入管道文件
}
close(fd2);
pthread_exit(NULL);
}
//子线程2用于读取管道1中的数据
void* READ(void* arg)
{
int fd1 = *(int *)arg;
while(1)
{
char buf[128]="";
read(fd1,buf,sizeof(buf));
if(!strcmp(buf,"bye"))
{
break;
}
printf("他对我说:%s\n",buf);
}
pthread_exit(NULL);
close(fd1);
}
int main(int argc, const char *argv[])
{
//打开两个管道文件
int fd1,fd2;
if((fd1=open("./fifo1",O_RDONLY))==-1)
{
perror("");
}
if((fd2=open("./fifo2",O_WRONLY|O_CREAT|O_TRUNC,0664))==-1)
{
perror("");
}
//创建两个子线程
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,WRITE,&fd2)==-1)
{
perror("");
return -1;
}
if(pthread_create(&tid2,NULL,READ,&fd1)==-1)
{
perror("");
return -1;
}
//回收子线程
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/894459964b1e4d02b1271b299ecd8e69.png)