实例——Linux管道pipe的使用

来源:互联网 发布:怎样批量删除淘宝订单 编辑:程序博客网 时间:2024/05/29 07:11

实例——Linux管道pipe的使用

Moakap总结

函数

#include <unistd.h>

int pipe(intfiledes[2]);

描述

       pipe()函数创建一个管道和指向该管道的一对文件描述符,并且将文件描述符存储到文件描述符数组filedes[]中。其中filedes[0]为读端,filedes[1]为写端。

返回值

       0– 管道创建成功;

       -1– 管道创建失败,同时errno置位;

错误指示

       EFAULT– 无效的输入参数filedes

       EMFILE– 达到当前进程允许的文件描述符最大值;

       ENFILE– 达到系统允许的打开文件的最大数;

实例

       下边的例子首先创建一个管道,然后通过fork()创建当先进程的子进程。接着每个进程关闭读写管道不需要的文件描述符。子进程在当前路径下执行“ls –a”命令,通过将管道写描述符fd[1]复制成标准输出,将命令执行输出写到管道;父进程通过fd[0]读取管道数据并显示。

#include <sys/wait.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{

   int fd[2];

   pid_t pid;

    charread_buffer[500] = {0};

    int read_count= 0;

    int status = 0;

     

   //创建管道

   if (pipe(fd) < 0)

    {

       printf("Create pipe failed.");

       return -1;

    }

 

   //创建子进程

   if ((pid = fork()) < 0)

    {

       printf("Fork failed.");

       return -1;

    }

 

   //子进程操作

   if (pid == 0)

    {

       printf("[child]Close read endpoint...");

       close(fd[0]);   /* 关闭不使用的读 文件描述符 */

 

       //复制fd[1]到标准输出

       if (fd[1] != STDOUT_FILENO)

       {

           if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)

           {

                return -1;

           }

 

           //close fd[1],标准输出即为fd[1]

           close(fd[1]);

       }

       

              //执行命令

       status = system("ls –a");

       if (status == -1)

       {

           return -1;

       }

    }

   else

    {

       printf("[parent]Close write endpoint...");

       //父进程 操作

       close(fd[1]);   /* 关闭不使用的写 文件描述符 */

 

       //从管道读数据

       read_count = read(fd[0], read_buffer, 500);

       printf("Content under current directory: /n%s", read_buffer);

    }

}

原创粉丝点击