zoukankan      html  css  js  c++  java
  • [转] IPC之管道、FIFO、socketpair

    管道和FIFO作为最初的UNIX IPC形式,现在已用得较少。SocketPair可作为全双工版本的管道,较为常用,这里简单做个笔记


    管道

    * 只用于有亲缘关系的进程间通信
    * 单向,即半双工 (双向方法:1 使用2个管道 2 使用SocketPair)

    * pipe() => write()/read()


    FIFO (有名管道)

    * 可用于无亲缘关系的进程间通信
    * 单向

    * mkfifo() => open() => write()/read()


    SocketPair

    * 套接字(一般用于网络通讯)提供的一种用于本机进程间通信方式
    * 双向,即全双工
    * socketpair() => write()/read()

    * 例子 [ SocketPair.cpp ]:

    #include <iostream>
    #include <stdlib.h>
    #include <string.h>
    #include <sys/types.h>
    #include <sys/socket.h>
    using namespace std;
    const int MAXSIZE = 100;
    
    int main()
    {
        int fd[2];
        int rLen;
        char wBuf[MAXSIZE] = "Hello World";
        char rBuf[MAXSIZE];
    
        if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd) < 0)
        {
            cout << "SocketPair Err" << endl;
            return -1;
        }
    
        pid_t pid = fork();
        if (pid < 0)
        {
            cout << "Fork Err" << endl;
            return -1;
        }
        
        if (pid == 0)
        {
            // Chlid
            cout << "Child, Pid=" << getpid() << endl;
            write(fd[0], wBuf, strlen(wBuf));
            write(fd[1], wBuf, strlen(wBuf));
            exit(-1);
        }
        
        // Parent
        sleep(1);
        cout << "Parent, Pid=" << getpid() << endl;
        rLen = read(fd[1], rBuf, MAXSIZE);
        rBuf[rLen] = 0;
        cout << "Read Fd[1], rBuf : " << rBuf << endl;
        rLen = read(fd[0], rBuf, MAXSIZE);
        rBuf[rLen] = 0;
        cout << "Read Fd[0], rBuf : " << rBuf << endl;
        return 0;
    }
    
    # g++ SocketPair.cpp 
    # ./a.out 
    Child, Pid=9569
    Parent, Pid=9568
    Read Fd[1], rBuf : Hello World
    Read Fd[0], rBuf : Hello World
  • 相关阅读:
    华硕笔记本无法U盘启动,快捷键识别不了
    怎么将uefi改成legacy启动|BIOS设置legacy引导模式的方法
    [CDLinux]制作U盘CDLinux系统启动盘
    重装系统时,将MBR分区转为GPT 分区
    5-Comments
    4-HTML Computer Code Elements
    3-html 缩写-地址-文字方向-引用块-题注的格式
    2-HTML Text Formatting Elements
    1-HTML Attributes
    LabVIEW--为设备添加配置文件.ini
  • 原文地址:https://www.cnblogs.com/qiangxia/p/4481166.html
Copyright © 2011-2022 走看看