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]。

  • 相关阅读:
    如何删除日志?
    sql lock
    生成DAL
    字符串ID替换
    精典SQL:分组合并列值
    SQL Server2005 XML数据类型基础
    Buckup
    SQL试题
    SQL处理表重复记录
    Left Join 中on与where的区别
  • 原文地址:https://www.cnblogs.com/gattaca/p/6546965.html
Copyright © 2011-2022 走看看