实现能够随时收发,即AB可以 随时 互相收发消息:提示 用多线程 或者多进程

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <pthread.h>

char buf[128] = "";
ssize_t res = 0;
pthread_t tid_r,tid_w;
//临界资源
void* callBack1(void* arg)
{
    //以写的方式打开fifo1
    int fd_w = open("./fifo1", O_WRONLY);
    if(fd_w < 0)
    {
        perror("open");
        return NULL;
    }
    while(1)
    {
        bzero(buf,sizeof(buf));
        printf("请输入>>>");
        scanf("%s", buf);
        while(getchar() != 10); //循环吸收垃圾字符
        if(write(fd_w, buf, sizeof(buf)) < 0)
        {
            perror("write");
            return NULL;
        }
        if(strcasecmp(buf, "quit") == 0)
            break;
    }
    close(fd_w);
    pthread_cancel(tid_w);
    pthread_exit(NULL);
}
void* callBack2(void* arg)
{

    //以读的方式打开fifo2
    int fd_r = open("./fifo2", O_RDONLY);
    if(fd_r < 0)
    {
        perror("open");
        return NULL;
    }
    while(1)
    {
        //向fifo1写入
        bzero(buf, sizeof(buf));
        //从fifo2读取
        res = read(fd_r, buf, sizeof(buf));
        if(res < 0)
        {
            perror("read");
            return NULL;
        }
        else if(0 == res)
        {
            printf("fifo2的写端关闭\n");
            break;
        }
        printf(":%s\n", buf);
        if(strcasecmp(buf, "quit") == 0)
            break;
    }
    close(fd_r);
    pthread_cancel(tid_r);
    pthread_exit(NULL);

}
int main(int argc, const char *argv[])
{
    //创建有名管道文件
    if(mkfifo("./fifo1", 0664) < 0) //向fifo1写入数据
    {
        if(17 != errno)
        {
            perror("mkfifo");
            return -1;
        }
    }
    if(mkfifo("./fifo2", 0664) < 0) //从fifo2读取数据
    {
        if(17 != errno)
        {
            perror("mkfifo");
            return -1;
        }
    }
    //创建线程1
    pthread_t tid1,tid2;
    if(pthread_create(&tid1,NULL,callBack1,NULL)!=0)
    {
        perror("pthread_create");
        return -1;
    }
    //创建线程2
    if(pthread_create(&tid2,NULL,callBack2,NULL)!=0)
    {
        perror("pthread_create");
        return -1;
    }
    pthread_join(tid_w,NULL);
    pthread_join(tid_r,NULL);
    return 0;
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值