Linux进程间通信:标准库中的管道操作

来源:互联网 发布:java class反编译工具 编辑:程序博客网 时间:2024/06/15 02:33

标准库中的管道操作

  • 使用popen()创建的管道必须使用pclose()关闭。其实,popen/pclose和标准文件输入/输出流中的fopen()/fclose()十分相似。
  • 封装管道的常用操作。
#include <stdio.h>
FILE *popen(const char * cmdstring,const char* type);
返回值:成功返回文件指针,出错返回NULL

int pclose(FILE *fp);
返回值:cmdstring的终止状态,出错返回-1.


#include <stdio.h>
#include <stdlib.h>
#include <memory.h>


int main(void)
{
    FILE *fp;


    fp = popen("cat /etc/passwd","r");
    char buf[512];
    memset(buf,0,sizeof(buf));
    while(fgets(buf,sizeof(buf),fp) != NULL){
        printf("%s",buf);
    }
    
    pclose(fp);
     
    printf("--------------------------------------------------\n");
    fp = popen("wc -l","w");


    fprintf(fp,"1\n2\n3\n");
    pclose(fp);


    return 0;
}