[LinuxC] 管道

本文介绍了LinuxC中的管道,包括管道的基本概念、特点和工作原理。讲解了如何创建和使用管道,以及在父子进程间共享管道的方法。同时讨论了管道的局限性和效率问题。还探讨了有名管道,特别是全双工有名管道的应用,强调了在管道读写时关闭不必要的文件描述符的重要性。
摘要由CSDN通过智能技术生成

管道

一种文件,因此可以使用IO函数对管道读写

  • 特点1:数据单向流动
  • 特点2:仅能用于父子进程/兄弟进程间的通信

使用管道可以来连接一个进程的输出和另一个进程的输入

管道的工作原理:管道是内核中的一个单项的数据通道。管道有一个读取端和写入端。

管道有缺陷:效率不高,是一个队列,导致缓冲大小受限,如果出现多个进程读取数据必然会出现数据读取不完整(Unix/Linux编程实践教程P321)

rtSwwj.md.png

1. 创建管道

#include <unistd.h>

result = pipe(int array[2]);

array[0]:读取端文件描述符 array[1]:写入端文件描述符

return 0->success -1 -> error

rtSqXD.png

2. 使用管道

  • Weird Demo – 同一进程间的管道

    /**
     * * Demostrates: how to create and use a pipe
     * * Effect: create a pipe, <process perspective> write into writing end, then runs around and reading from
     *   reading end. A litte weird, but demostrates the idea.
     *  
     *   result = pipe(int array[2]);
     *   array[0]:读取端文件描述符  array[1]:写入端文件描述符
    */
    
    #include <stdio.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main()
    {
         
        int aPipe[2];
        char buf[BUFSIZ];
    
        int result;
    
        // create a pipe
        if(result = pipe(aPipe)){
         
            perror("Create pipe fail.\n");
            exit(1);
        }
    
        printf("Create pipe sucessfully! It's file descriptor: {%d, %d}\n", aPipe[0], aPipe[1]);
    
        // illustrate
        // read from stdin, write into pipe, read from pipe, and print on screen(stdout)
        // https://s3.ax1x.com/2020/12/19/rNXBHs.png this pic shows how data transports
        while(fgets(buf, BUFSIZ, stdin)){
         
            int len = strlen(buf);
            // write buf into pipe
            if( write(aPipe[1], buf, len) != len){
         
                perror("write into pipe");
                break;
            }
    
            // read data from pipe
            len = read(aPipe[0], buf, len);
            if(len == -1){
         
                perror("reading from pipe");
                break;
            }
    
            // print on screen (write data into stdout)
            if(write(STDOUT_FILENO, buf, len) != len){
         
                perror("writing to stdout");
                break;
            }
        }
    
    }
    
  • 使用pipe & fork在两个进程间共享管道

    rNxwuD.md.png

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>

int main()
{
   
    int aPipe[2];
    char buf[BUFSIZ];

    if(pipe(aPipe) ==</
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值