本文主要是介绍Linux-实现没有血缘关系的进程之间的通信,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
目录
一.makefile的编写
二.comm.hpp头文件的编写
三.serve.cc文件的编写
四.client.cc文件的编写
一.makefile的编写
.PHONY:all
all:serve clientserve : serve.ccg++ -o $@ $^ -g -std=c++11
client : client.ccg++ -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;}elsebreak;}//关闭命名管道文件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;
}
这篇关于Linux-实现没有血缘关系的进程之间的通信的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!