C语言:通过线程和有名管道,实现进程间全双工通信

代码示例:

(head.h)

#ifndef _HEAD_H
#define _HEAD_H

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/wait.h>
#include<fcntl.h>
#include<pthread.h>
#include<semaphore.h>

#endif

(write.c)

#include"head.h"

int fdA = 0;
int fdB = 0;
char tmpbuff[1024] = {0};

void *threadA(void *arg)
{
    while (1)
    {
        memset(tmpbuff, 0, sizeof(tmpbuff));
        gets(tmpbuff);
        write(fdA, tmpbuff, strlen(tmpbuff));
        
        if (!strcmp(tmpbuff, "quite"))
        {
            break;
        }
    }
    return NULL;
}

void *threadB(void *arg)
{
    while (1)
    {
        memset(tmpbuff, 0, sizeof(tmpbuff));
        read(fdB, tmpbuff, sizeof(tmpbuff));
        printf("B: %s\n", tmpbuff);

        if (!strcmp(tmpbuff, "quite"))
        {
            break;
        }
    }
    return NULL;
}

int main(void)
{
    pthread_t tidA;
    pthread_t tidB;

    mkfifo("/tmp/myfifoA", 0664);
    
    fdA = open("/tmp/myfifoA", O_WRONLY);
    if (-1  == fdA)
    {
        perror("open");
        exit(1);
    }

    fdB = open("/tmp/myfifoB", O_RDONLY);
    if (-1 == fdB)
    {
        perror("open");
        exit(1);
    }

    pthread_create(&tidA, NULL, threadA, NULL);
    pthread_create(&tidB, NULL, threadB, NULL);

    pthread_join(tidA, NULL);
    pthread_join(tidB, NULL);
    
    close(fdA);
    close(fdB);
    return 0;
}

(read.c)

#include"head.h"

int fdA = 0;
int fdB = 0;
char tmpbuff[1024] = {0};

void *threadA(void *arg)
{
    while (1)
    {
        memset(tmpbuff, 0, sizeof(tmpbuff));
        read(fdA, tmpbuff, sizeof(tmpbuff));
        printf("A: %s\n", tmpbuff);

        if (!strcmp(tmpbuff, "quite"))
        {
            break;
        }
    }
    return NULL;
}

void *threadB(void *arg)
{
    while (1)
    {
        memset(tmpbuff, 0, sizeof(tmpbuff));
        gets(tmpbuff);
        write(fdB, tmpbuff, strlen(tmpbuff));
        
        if (!strcmp(tmpbuff, "quite"))
        {
            break;
        }
    }
    return NULL;
}

int main(void)
{
    pthread_t tidA;
    pthread_t tidB;

    mkfifo("/tmp/myfifoB", 0664);
  
    fdA = open("/tmp/myfifoA", O_RDONLY);
    if (-1 == fdA)
    {
        perror("open");
        exit(1);
    }

    fdB = open("/tmp/myfifoB", O_WRONLY);
    if (-1 == fdB)
    {
        perror("open");
        exit(1);
    }
  
    pthread_create(&tidA, NULL, threadA, NULL);
    pthread_create(&tidB, NULL, threadB, NULL);

    pthread_join(tidA, NULL);
    pthread_join(tidB, NULL);

    close(fdA);
    close(fdB);
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值