有名管道的应用

通过创建两个管道可以实现进程间的全双工通信,同样也可以通过创建两个FIFO来实现不同进程间的全双工通信。

Server端
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>

#define FIFO_READ   "readfifo"
#define FIFO_WRITE  "writefifo"
#define BUF_SIZE    1024

int main(int argc, char *argv[])
{
    int wfd, rfd;
    char buf[BUF_SIZE];
    int len;

    umask(0);
    if (mkfifo(FIFO_WRITE, S_IFIFO | 0666)) {
        printf("Can't create FIFO %s because %s",FIFO_WRITE,strerror(errno));
        exit(1);
    }

    umask(0);
    wfd = open(FIFO_WRITE,O_WRONLY);
    if (wfd == -1) {
        printf("open FIFO %s error: %s",FIFO_WRITE,strerror(errno));
        exit(1);
    }

    while ((rfd = open(FIFO_READ,O_RDONLY)) == -1) {
        sleep(1);
    }

    while (1) {
        printf("Server: ");
        fgets(buf, BUF_SIZE, stdin);
        buf[strlen(buf)-1] = '\0';
        if (strncmp(buf, "quit", 4) == 0) {
            close(wfd);
            unlink(FIFO_WRITE);
            close(rfd);
            exit(0);
        }
        write(wfd,buf,strlen(buf));
        len = read(rfd, buf, BUF_SIZE);
        if (len > 0) {
            buf[len] = '\0';
            printf("Client: %s\n",buf);
        }
    }
    return 0;
}
Client端
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>

#define FIFO_READ   "writefifo"
#define FIFO_WRITE  "readfifo"
#define BUF_SIZE    1024

int main(int argc, char *argv[])
{
    int wfd, rfd;
    char buf[BUF_SIZE];
    int len;

    umask(0);
    if (mkfifo(FIFO_WRITE, S_IFIFO | 0666)) {
        printf("Can't create FIFO %s because %s",FIFO_WRITE,strerror(errno));
        exit(1);
    }

    while ((rfd = open(FIFO_READ, O_RDONLY)) == -1) {
        sleep(1);
    }

    wfd = open(FIFO_WRITE, O_WRONLY);
    if (wfd == -1) {
        printf("Fail to open FIFO %s : %s",FIFO_WRITE,strerror(errno));
        exit(-1);
    }

    while (1) {
        len = read(rfd, buf, BUF_SIZE);
        if (len > 0) {
            buf[len] = '\0';
            printf("Server: %s\n",buf);
        }
        printf("Client: ");
        fgets(buf, BUF_SIZE, stdin);
        buf[strlen(buf)-1] = '\0';
        if (strncmp(buf, "quit", 4) == 0) {
            close(wfd);
            unlink(FIFO_WRITE);
            close(rfd);
            exit(0);
        }
        write(wfd, buf, strlen(buf));
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值