zoukankan      html  css  js  c++  java
  • 进程间通信之管道

    管道(pipe)是进程间通信的一种方式。

    API:

    int pipe(int pipefd[2]);

    DEMO:

    #include <sys/types.h>
    #include <sys/wait.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <string.h>
    
    #define MAXLINE 4096
    
    int main(int argc, char **argv) {
        int n;
        int fd[2];
        pid_t pid;
        char line[MAXLINE];
        
        if (pipe(fd) < 0) {
            perror("pipe error");
            exit(1);
        }
        if ( (pid = fork()) < 0) {
            perror("fork error");
            exit(1);
        } else if (pid > 0) {
            close(fd[0]);
            write(fd[1], "hello world
    ", 12);
        } else {
            close(fd[1]);
            n = read(fd[0], line, MAXLINE);
            write(STDOUT_FILENO, line, n);
        }
        exit(0);
    }

    管道的特点:

    1. 管道是半双工的(数据只能在一个方向上流动)

    2. 管道只能在具有公共祖先的两个进程之间使用

    对于从父进程到子进程的管道,父进程关闭管道的读端fd[0],子进程关闭写端fd[1]。

    对于从子进程到父进程的管道,父进程关闭fd[1],子进程关闭fd[0]。

  • 相关阅读:
    VUE.js入门学习(2)-基础精讲
    VUE中的MVVM模式
    VUE.js入门学习(1)-起步
    Vuex 是什么
    Proxy
    VUE常见的语法
    ES6的一些语法
    Element
    Mock.js
    第一阶段:Python开发基础 day14 三元表达式 生成器 匿名函数
  • 原文地址:https://www.cnblogs.com/gattaca/p/6546965.html
Copyright © 2011-2022 走看看