进程间通信


目录
  • 说明
  • 无名管道
  • 命名管道
  • 内存映射
  • 消息队列
  • 共享内存
  • 信号量
  • 信号

说明


无名管道(pipe)
命名管道(fifo)
内存映射(mapped memeory),
消息队列(message queue)
共享内存(shared memory)
信号量(semaphore)
信号(signal)
文件(file)
套接字(Socket)

无名管道

在具有亲缘进程间的单向管道
读写的是一个
注意控制,流向的方法

#include 
#include 
#include 
#include 
#include 
#include 
#include 

int main() {
    using std::cout;
    using std::endl;
    using std::string;
    using std::to_string;
    int pipe_fd[2];
    const int MAX_BUF_LENGTH = 256;
    char buf[MAX_BUF_LENGTH];
    string  data  = "Pip test program";
    
    memset(buf,0,sizeof(buf));
    if (pipe(pipe_fd) < 0) {
        cout << "Pipe create error.\n";
        exit(1);
    }
    else {
        pid_t pid = fork();
        if (pid == 0) {
            close(pipe_fd[1]);
            int real_read;
            if ((real_read = read(pipe_fd[0],buf,MAX_BUF_LENGTH)) > 0) {
                cout << "get = [" << real_read << "] = " << buf << "\n";
            }
            close(pipe_fd[0]);
            return 0;
        }
        else if (pid > 0) {
            close(pipe_fd[0]);
            int real_write;
            if ((real_write = write(pipe_fd[1],data.c_str(),data.size())) != -1) {
                cout << "send = [" << real_write << "] = " << data << endl;
            }
            close(pipe_fd[1]);
            wait(0);
            return 0;
        }
        else {
            cout << "Unknow pid = " << pid << endl;
        }
    }
    return 0;
}

命名管道

内存映射

消息队列

共享内存

信号量

信号

相关