popen使用FIFO管道执行外部程序。
#include <stdio.h>
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);
popen 通过type是 r 还是 w 确定command的输入/输出方向,r和w是相对command的管道而言的。r表示command从管道中读入,w表示 command通过管道输出到它的stdout,popen返回FIFO管道的文件流指针。pclose则用于使用结束后关闭这个指针。
例子一:
/*使用popen来执行“ps -ef”命令*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#define BUFSIZE 1000
int main()
{
FILE *fp;
char *cmd = "ps -ef";
char buf[BUFSIZE];
buf[BUFSIZE] = '\0';
/*调用popen函数执行相应的命令*/
if((fp=popen(cmd,"r"))==NULL)
perror("popen");
while((fgets(buf,BUFSIZE,fp))!=NULL)
printf("%s",buf);
pclose(fp);
exit(0);
}
例子二:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char buf[200] = {0};
if((fp = popen("cat > test1", "w")) == NULL)
{
perror("Fail to popen\n");
exit(1);
}
fwrite("Read pipe successfully !", 1, sizeof("Read pipe successfully !"), fp);
pclose(fp);
return 0;
}