Linux/UNIX学习之管道

pipe()调用来创建一个新管道。

#include <unistd.h>
int pipe(int filedes[2])

成功的调用pipe()会在数组filedes中返回两个打开的文件描述符:一个表示管道的读取端(filedes[0]),另一个表示管道的写入端(filedes[1])。

事例程序:

演示如何将管道用于父子进程间的通讯——父进程在一个操作中写入数据,子进程在一个操作中一小块一小块地从管道中读取数据。

#include <sys/wait.h>
#include "tlpi_hdr.h"(可删除)

#define BUF_SIZE 10

int main(int argc,char*argv[])
{
    int pfd[2];
    char buf[BUF_SIZE];
    ssize_t numRead;

    if(argc != 2|| strcmp(argv[1],"--help") == 0)
        printf("%s string\n",argv[0]);

    if(pipe(pfd) == -1)
    {
        printf("pipe");
    }

    switch(fork()){

    case -1:
         printf("close - child");
    case 0:
         if(close(pfd[1])== -1)
              printf("close -child");
         for(;;)
             {
                numRead = read(pfd[0],buf,BUF_SIZE);
                if(numRead == -1)
                    printf("read");
                if(numRead == 0)
                    break;
                if(write(STDOUT_FILENO,buf,numRead)!=numRead)
                   printf("child - partial/failed write");
             }
         write(STDOUT_FILENO,"\n",1);
         if(close(pdf[0])==-1)
             printf("close");
         _exit(EXIT_SUCCESS);
    default:
         if(close(pfd[0]) == -1)
             printf("close-parent");
         if(write(pdf[1],argv[1],strlen(argv[1]))!=strlen(argv[1]))
             printf("parent-partial/failed write");
         if(close(pdf[1]) == -1)
             printf("close");
         wait(NULL);
         exit(EXIT_SUCCESS);
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值