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 <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <pthread.h>
using namespace std;
//int main()
//{
// //cout << "Hello world!" << endl;
// FILE* fout;
// char cmd[256]={0};
// //puts("input a cmd!");
// fgets(cmd,sizeof(cmd),stdin);
// //cout << cmd;
// fout = popen(cmd,"r");
// if(!fout)
// puts("popen error!");
// char sBuf[256];
// while(true)
// {
// memset(sBuf,0x00,sizeof(sBuf));
// fgets(sBuf,sizeof(sBuf),fout);
// if(!strlen(sBuf))
// break;
// puts(sBuf);
//
// //return 0
//
// }
// return 0;
//}
int main()
{
//fopen w
FILE * fin;
char sBuf[256];
//int nRet=pthread_create();
while(true)
{
fin = popen("sh","w");
if(!fin)
cout <<"popen error!" << endl;
memset(sBuf,0x00,sizeof(sBuf));
puts("input cmd:");
fgets(sBuf,sizeof(sBuf),stdin);
fputs(sBuf,fin);
fputs(" > tt.txt",fin);
fputs("exit",fin);
system("cat tt.txt;rm tt.txt");
pclose(fin);
}
return 0;
}
popen用的管道通信,所以只能读或者写,不能同时进行.
上面的popen的第一个参数可以是可执行文件,可执行文件名就是一条命令。
联想一下 find . -name *.h | grep hehe
。。。。。。。。。。。。。。