c语言中一说调用系统命令,都会想起system,这是system的用法
int system(char *command);
因此可见system返回的是一个int型的变量,并不是该命令的执行结果,因此需要另外的函数popen来实现
表头文件
#include
函数定义
FILE * popen ( const char * command , const char*type );
函数说明:popen()会调用fork()产生子进程,然后从子进程中调用/bin/sh -c 来执行参数command 的指令。
参数type 可使用 "r"代表读取,"w"代表写入。依照此type 值,popen()会建立管道连到子进程的标准输出设备或标准输入设备,然后返回一个文件指针。随后进程便可利用此文件指针来读取子进程的输出设备或是写入到子进程的标准输入设备中。
此外,所有使用文件指针(FILE*)操作的函数也都可以使用,除了fclose()以外。
返回值:若成功则返回文件指针, 否则返回NULL, 错误原因存于errno 中.
错误代码:EINVAL 参数type 不合法。
注意事项:在编写具 SUID/SGID 权限的程序时请尽量避免使用popen()、popen()会继承环境变量,通过环境变量可能会造成系统安全的问题。
int pclose ( FILE * stream );
举例:c语言调用ls命令,获取ls的执行结果
#include
int main(int argc,char *argv[])
{
FILE *fp;
char ch;
fp = popen("ls","r");
while((ch=fgetc(fp))!=EOF) //该程序将结果输出到屏幕,其它形式类似,保存到变量,strcpy就可以了
{
printf("%c",ch);
}
/*
char buffer[80];
fgets(buffer, sizeof(buffer), fp);
printf("%s", buffer);
*/ pclose(fp);
}
################################3
voidexecuteCMD(constchar*cmd,char*result)
{
charbuf_ps[1024];
charps[1024]={0};
FILE*ptr;
strcpy(ps, cmd);
if((ptr=popen(ps,"r"))!=NULL)
{
while(fgets(buf_ps, 1024, ptr)!=NULL)
{
strcat(result, buf_ps);
if(strlen(result)>1024)
break;
}
pclose(ptr);
ptr = NULL;
}
else
{
printf("popen %s error\n", ps);
}
}