linux的C获取shell执行返回的结果
来源:互联网 发布:网络诈骗学生自杀 编辑:程序博客网 时间:2024/05/02 04:28
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
- linux的C获取shell执行返回的结果
- Linux C 程序执行 shell 命令并获取返回结果的方法
- Linux C 执行shell命令并获取返回结果
- linux的C程序 调用 shell脚本,获取shell的执行结果
- C语言获取Shell返回结果的实现方法
- Linux中用C语言执行shell命令并获取返回结果
- linux Shell编程--获取命令执行返回结果
- BuildForge获取Linux shell命令执行的返回值
- 获取python执行shell命令的结果
- Perl 获取shell命令的执行结果
- popen C函数获取linux命令的执行结果
- C程序中如何获取shell命令执行结果和返回值
- linux shell命令的结果获取
- linux shell变量获取执行结果
- MSSQOSERVER 获取执行动态语句返回的结果
- 在shell中获取sql的执行结果
- linux shell命令中字符串的连接,及获取执行命令后返回的字符
- Linux C语言获得执行的shell命令的返回值
- arcgis server 10和win7地图不显示,显示空白,toc控件图片不显示
- 任务二第七个
- 苹果前CEO斯卡利变身创业导师:欲寻下个乔布斯
- IOS文档
- webkit几个依赖库在windows下的编译方法
- linux的C获取shell执行返回的结果
- LTORG
- 忠告:创业公司与大公司正面竞争易死
- 解决struts1中请求跳转到Action而非execute的问题
- 插入排序 和 归并排序(分治)的c实现和时间复杂度分析
- 美媒:小米新浪达成合作 采取行动对抗腾讯
- 三大WEB服务器对比分析(apache ,lighttpd,nginx)
- iOS学习笔记08—多线程概述
- linux 强大工具: Vim 学习一