#include<stdio.h>
FLIE * fp = popen(“ls -l”,“r”);失败为空,只要是指针的类型,返回值均为空,只要是判断的函数,失败为0,成功为1;
fread(buf , sizeof(char),sizeof(buf),fp); 把结果定向到 buf 里面
popen() 与exec 族函数不同的是,popen()还是要转回来 执行自己的函数
// add.c
#include <stdio.h>
int main()
{
int i , j;
scanf("%d%d",&i ,&j);
printf("sum = %d\n",i+j);
return 0;
}
//p.c
#include <stdio.h>
int main()
{
int i, j;
printf("Hello world\n");
return 0;
}
// popen_w.c
#include <stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
FILE * fp = popen("./add", "w");
if ( fp ==NULL )
{
printf("popen is wrong \n");
}
char buf[128]="3 4";
fwrite(buf,sizeof(char),sizeof(buf),fp); // 将buf 的内容餐位参数,写入 add.c的参数中
pclose(fp);
FILE *fp2 = popen("./p","r");
fread(buf,sizeof(char),sizeof(buf),fp2); //将输出到屏幕上的内容输出到buf里面
printf("buf = %s",buf);
printf("popen_w.c is over\n");
pclose(fp2);
}
int main()
{
FILE * fp = popen ( "ls -l","r"); // 将命令行的命令写入到 buf中
// FILE * fp = popen("ls", "r");
if ( fp ==NULL )
{
printf("popen is wrong \n");
}
char buf[128]={0};
int ret= fread(buf,sizeof(char), sizeof(buf), fp);
if( ret == -1 )
{
printf("fread is wrong \n");
}
printf("buf[127]=%c\n",buf[127]);
printf("buf= %s\n",buf);
}