操作系统实践——基于Linux的应用与内核编程7.2无名管道的使用方法

本节给出本书P90页例子

内容包括popenpclose的使用方法

出现过的问题:

warning: incompatible implicit declaration of built-in function ‘memset’ [enabled by default]
     memset(buf,'\0',sizeof(buf));   //初始化缓冲区
     ^
poprn_test1.c:26:9: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default]
         exit(0);
         ^
poprn_test1.c:28:5: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default]
     exit(1);

原因:开始没有包含头文件,加上<stdlib.h> 和 <string.h>试试

最终样例如下:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    FILE *fpr = NULL;
    FILE *fpw = NULL;
    char buf[BUFSIZ + 1];
    int len = 0;
    memset(buf,'\0',sizeof(buf));   //初始化缓冲区

    fpr = popen("ls -l","r");
    fpw = popen("grep rwx","w");
    if(fpr&&fpw){
        len = fread(buf,sizeof(char),BUFSIZ,fpr);
        while(len > 0)          //还有数据可读,循环读取数据,直到读完所有数据
        {
            buf[len] = '\0';
            //把数据写入grep进程
            fwrite(buf,sizeof(char),len,fpw);
            len = fread(buf,sizeof(char),BUFSIZ,fpr);
        }
        pclose(fpr);
        pclose(fpw);
        exit(0);
    }
    exit(1);
}

实现的功能不是ls -l|grep rwx,一开始我理解错了,

后来发现是grep rwx|ls -l

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值