zoukankan      html  css  js  c++  java
  • linux中用无名管道进行文件的读写

    1管道是什么:

      水管子大家知道,有两端,在此一端用来读一端用来写,其中一端的输出作为另外一端的输入。

    2 函数原型

      int pipe(int pipefd[2]);//参数中分别代表的两端

    3 例子:管道一端作为写 另外一端作为读 父子进程实现

     1 #include <unistd.h>
     2 #include <stdio.h>
     3 #include <stdlib.h>
     4 
     5 int main()
     6 {
     7     pid_t pid;
     8     int temp;
     9     int pipedes[2];
    10     char s[14]="letgo";
    11     char d[14];
    12     if((pipe(pipedes))==-1)
    13     {
    14         perror("pipe");
    15         exit(EXIT_FAILURE);
    16     }
    17     
    18     if((pid=fork())==-1)
    19     {
    20         perror("fork error");
    21         exit(EXIT_FAILURE);
    22     }else if(pid==0)
    23     {
    24         //printf(“子进程写数据到管道读端”);
    25         printf("子进程写数据到管道读端
    ");
    26         if((write(pipedes[1],s,14))==-1)
    27         {
    28             perror("write");
    29             exit(EXIT_FAILURE);
    30         }else
    31         {
    32             printf("所写入得数据是%s
    ",s);
    33             exit(EXIT_SUCCESS);
    34         }
    35     }else if(pid>0)
    36     {
    37         sleep(2);//等待子进程结束
    38         printf("父进程从管道读数据
    ");
    39         if((read(pipedes[0],d,14))==-1)
    40         {
    41             perror("read");
    42             exit(EXIT_FAILURE);
    43         }
    44         printf("从管道读端读出得数据是%s
    ",d);
    45     }
    46     
    47     return 1;
    48 }

    运行结果:

  • 相关阅读:
    postfix队列管理
    fdisk添加磁盘
    postfix日志分析pflogsumm
    ioctl接口内容操作
    linux 路由表设置 之 route 指令详解
    手把手教你用 Strace 诊断问题
    rtsp学习----海康RTSP客户端连接深入分析
    栈回溯技术
    objdump命令
    linux中的strip命令简介------给文件脱衣服
  • 原文地址:https://www.cnblogs.com/lanjianhappy/p/6875896.html
Copyright © 2011-2022 走看看