popen()函数原型如下:
FILE *popen(const char *cmd,const char *type);
返回值:若成功返回文件指针,出错则返回NULL
功能:创建一个管道,fork一个子进程,接着关闭管道的不使用端,子进程执行cmd指向的应用程序或者命令。
执行完该函数后父进程和子进程之间生成一条管道,函数返回值为FILE结构指针,该指针作为管道的一端,为父进程所拥有。子进程则拥有管道的另一端,该端口为子进程的stdin或者stdout。如果type=r,那么该管道的方向为:子进程的stdout到父进程的FILE指针;如果type=w,那么管道的方向为:父进程的FILE指针到子进程的stdin。
example:
#include <stdio.h>
#include <string.h>
int main( void )
{
FILE *stream;
char buf[1024];
stream = popen( "ls -l", "r" ); //将“ls -l”命令的输出 通过管道读取(“r”参数)到FILE* stream
fread( buf, sizeof(char), sizeof(buf), stream); //将刚刚FILE* stream的数据流读取到buf中
printf("%s\n", buf); //直接输出到屏幕上
pclose( stream );
return 0;
}