您的位置:首页 > 运维架构 > Shell

linux的C程序 调用 shell脚本,获取shell的执行结果

2014-06-21 01:16 871 查看
linux下通过C执行命令的时候一半都是使用system()方法,但是该方法执行命令返回的值是-1或0,而有时候我们需要得到执行命令后的结果。可以使用管道实现

输出到文件流的函数是popen(),例如

FILE *isr;

isr = popen("ls -l","r"); ls -l命令的输出通过管道读取("r"参数)到isr

下面是演示例子,列出当前可用的loop设备,(必须是root权限才可以执行losetup -f)

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

char* cmd_system(const char* command);
int main()
{
//char str[20]={"0"};
char* result = cmd_system("losetup -f");
//通过该方法可以将char*转换为char数组
//strcpy(str,result);
printf("The result:%s\n",result);
return 0;
}

char* cmd_system(const char* command)
{
char* result = "";
FILE *fpRead;
fpRead = popen(command, "r");
char buf[1024];
memset(buf,'\0',sizeof(buf));
while(fgets(buf,1024-1,fpRead)!=NULL)
{
       result = buf;
}
if(fpRead!=NULL)
pclose(fpRead);
return result;
}


执行结果:

The result:/dev/loop0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: