IO DAY 7

该程序展示了如何使用C语言创建一个简单的双人聊天室,通过管道(fifo)进行进程间的通信。程序包含两个进程,每个进程有读和写两个线程。读线程从管道读取数据,写线程将用户输入的数据写入管道,当用户输入bye时,通信结束。
摘要由CSDN通过智能技术生成

双人聊天室:

#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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值