日常学习

发布时间 2023-04-19 21:12:13作者: Yin-SHT

2023/4/19

POPEN & PCLOSE

  1. 函数原型
    FILE *popen(const char *command, const char *type);
    int pclose(FILE *stream);
    
  2. 函数行为
    popen函数(常用)建立管道,fork子进程,调用sehll执行命令。
    pclose函数关闭由popen函数返回的I/O文件流。
  3. 参数解释
    type: r表示command的标准输出是管道,父进程利用文件指针从管道中读取数据。w表示command的标准输入是管道,父进程利用文件指针向管道中写入数据。
    command: I/O文件指针。
  4. 应用示例
#include <stdio.h>

int main( int argc, char **argv ) {
    FILE *r_fp = popen( "ls", "r" );
    FILE *w_fp = popen( "wc -l", "w" );
    char buf[ 65536 ] = { 0 }; 

    while ( ( fgets( buf, sizeof( buf ), r_fp ) ) != NULL ) {
        fputs( buf, w_fp );
    }

    pclose( r_fp );
    pclose( w_fp );

    return 0;
}

SYSTEM