Linux-实现没有血缘关系的进程之间的通信

目录

一.makefile的编写        

二.comm.hpp头文件的编写

三.serve.cc文件的编写

四.client.cc文件的编写


一.makefile的编写        

.PHONY:all
all:serve client

serve : serve.cc
	g++ -o $@ $^ -g -std=c++11
client : client.cc
	g++ -o $@ $^ -g -std=c++11

.PHONY:clean
clean:
	rm -rf serve client

二.comm.hpp头文件的编写

#pragma once

#include <cstdio>
#include <cerrno>
#include <string>
#include <cstring>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>

using namespace std;

#define SIZE      1024
#define MODE      0664
#define FIFO_FILE "./myfifo"


enum
{
    FIFO_CREATE_ERR = 1,
    FIFO_DELETE_ERR,
    FIFO_OPEN_ERR
};

三.serve.cc文件的编写

#include "comm.hpp"

int main(void)
{
    //创建命名管道文件
    int n = 0;
    n = mkfifo(FIFO_FILE, MODE);
    if(-1 == n)
    {
        perror("mkfifo");
        exit(FIFO_CREATE_ERR);
    }

    //以读的方式打开管道文件
    int fd = open(FIFO_FILE, O_RDONLY);
    if(fd < 0)
    {
        perror("open");
        exit(FIFO_OPEN_ERR);
    }
    cout << "serve open file done" << endl;

    //进行没有血缘关系的进程之间的通信
    while(true)
    {
        char buffer[SIZE];

        int read_number = 0;
        read_number = read(fd, buffer, sizeof(buffer));
        if (read_number > 0)
        {
            buffer[read_number] = 0;
            cout << "client say# " << buffer << endl;
        }
        else if (read_number == 0)
        {
            printf("client quit, me too !");
            break;
        }
        else
            break;

    }

    //关闭命名管道文件
    close(fd);

    //删除管道文件
    n = unlink(FIFO_FILE);
    if(-1 == n)
    {
        perror("unlink");
        exit(FIFO_DELETE_ERR);
    }
    return  0;
}

四.client.cc文件的编写

#include "comm.hpp"

int main(void)
{
    //以写的方式打开命名管道文件
    int fd = open(FIFO_FILE, O_WRONLY);
    if(fd < 0)
    {
        perror("open");
        exit(FIFO_OPEN_ERR);
    }
    cout << "client open file done" << endl;

    //进行没有血缘关系的进程之间的通信
    string client_str;
    while(true)
    {
        cout << "Please Enter@ ";
        getline(cin, client_str);

        write(fd, client_str.c_str(), client_str.size());
    }

    //关闭命名管道文件
    close(fd);

    return  0;
}

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值