本节给出本书P90页例子
内容包括popen、pclose的使用方法
出现过的问题:
warning: incompatible implicit declaration of built-in function ‘memset’ [enabled by default]memset(buf,'\0',sizeof(buf)); //初始化缓冲区
^
poprn_test1.c:26:9: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default]
exit(0);
^
poprn_test1.c:28:5: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default]
exit(1);
原因:开始没有包含头文件,加上<stdlib.h> 和 <string.h>试试
最终样例如下:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *fpr = NULL;
FILE *fpw = NULL;
char buf[BUFSIZ + 1];
int len = 0;
memset(buf,'\0',sizeof(buf)); //初始化缓冲区
fpr = popen("ls -l","r");
fpw = popen("grep rwx","w");
if(fpr&&fpw){
len = fread(buf,sizeof(char),BUFSIZ,fpr);
while(len > 0) //还有数据可读,循环读取数据,直到读完所有数据
{
buf[len] = '\0';
//把数据写入grep进程
fwrite(buf,sizeof(char),len,fpw);
len = fread(buf,sizeof(char),BUFSIZ,fpr);
}
pclose(fpr);
pclose(fpw);
exit(0);
}
exit(1);
}
实现的功能不是ls -l|grep rwx,一开始我理解错了,
后来发现是grep rwx|ls -l