管道是Linux支持的最初Unix IPC形式之一。
管道是半双工的,数据只能向一个方向流动;
一个管道只能负责一个方向的数据传输。
需要双方通信时,需要建立起两个管道;
只能用于父子进程或者兄弟进程之间(具有亲缘关系的进程);
假如进程A与进程b通信,需要建立两个管道:
一个管道只能用于一个方向的通信,其另外的方向需要关闭.
封装的管道类,头文件:
#ifndef CPIPE_H #define CPIPE_H #include <cstddef> #define SOCKET int #define INVALID_SOCKET (SOCKET)(~0) class TPipe { public: TPipe(void); ~TPipe(void) { close(); } bool open(bool boCanbeInherit = false); void close(void) { closeReadHandle(); closeWriteHandle(); } int read(void * lpBuff,size_t nLength); int write(const void * lpBuff,size_t nLength); SOCKET getReadHandle(void) const { return m_nPipe[READHANDLE_INDEX]; } SOCKET getWriteHandle(void) const { return m_nPipe[WRITEHANDLE_INDEX]; } void closeReadHandle(void) { closeImp(READHANDLE_INDEX); } void closeWriteHandle(void) { closeImp(WRITEHANDLE_INDEX); } protected: enum { READHANDLE_INDEX = 0, WRITEHANDLE_INDEX = 1, }; void closeImp(int nIndex); SOCKET m_nPipe[2]; }; class TPipePair { public: TPipePair(void); ~TPipePair(void); bool initEx(void); void close(void) { m_Comm[0].close(); m_Comm[1].close(); } void CloseInA(void) { m_Comm[0].closeReadHandle(); m_Comm[1].closeWriteHandle(); } void BCloselnB(void) { m_Comm[0].closeWriteHandle(); m_Comm[1].closeReadHandle(); } SOCKET getAProReadHandle(void) { return m_Comm[1].getReadHandle(); } SOCKET getAProWriteHandle(void) { return m_Comm[0].getWriteHandle(); } SOCKET getBProReadHandle(void) { return m_Comm[0].getReadHandle(); } SOCKET getBProWriteHandle(void) { return m_Comm[1].getWriteHandle(); } protected: enum { MASTER_2_SUBMGR = 0x00, SUBMGR_2_MASTER = 0x01, }; TPipe m_Comm[2]; }; #endif // CPIPE_H
源文件:
#include "cpipe.h" #include <unistd.h> TPipe::TPipe(void) { m_nPipe[0] = INVALID_SOCKET; m_nPipe[1] = INVALID_SOCKET; } void TPipe::closeImp(int nIndex) { if (m_nPipe[nIndex] != INVALID_SOCKET) ::close(m_nPipe[nIndex]); m_nPipe[nIndex] = INVALID_SOCKET; } bool TPipe::open(bool boCanbeInherit) { if (pipe(m_nPipe) == -1) return false; return true; } int TPipe::read(void * lpBuff,size_t nLength) { if (m_nPipe[READHANDLE_INDEX] == INVALID_SOCKET) return -1; return ::read(m_nPipe[READHANDLE_INDEX],lpBuff,nLength); } int TPipe::write(const void * lpBuff,size_t nLength) { if (m_nPipe[WRITEHANDLE_INDEX] == INVALID_SOCKET) return -1; return ::write(m_nPipe[WRITEHANDLE_INDEX],lpBuff,nLength); } TPipePair::TPipePair(void) { } TPipePair::~TPipePair(void) { } bool TPipePair::initEx(void) { TPipePair::close(); if (!m_Comm[SUBMGR_2_MASTER].open()) return false; else if (!m_Comm[MASTER_2_SUBMGR].open()) return false; }
原文地址:http://mingtangduyao.blog.51cto.com/4876371/1722782