目录
一.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;
}