C语言获取Shell返回结果的实现方法
2016-07-01 11:11
806 查看
Linux编程时候,如果我们需要调用shell命令或脚本通常使用system方法。如system("ls")
该方法返回值为0或-1,即成功或失败。而有的时候我们想要获取shell命令执行的结果,该怎么办呢?
我们可以将shell命令结果重定向到文件中,然后再读取这个文件,如:
system("ls>result.txt")
FILE *fp = fopen(result, "r")
当然我们也可以直接使用管道,如下面示例:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <strings.h> #include <string.h> char* shellcmd(char* cmd, char* buff, int size) { char temp[256]; FILE* fp = NULL; int offset = 0; int len; fp = popen(cmd, "r"); if(fp == NULL) { return NULL; } while(fgets(temp, sizeof(temp), fp) != NULL) { len = strlen(temp); if(offset + len < size) { strcpy(buff+offset, temp); offset += len; } else { buff[offset] = 0; break; } } if(fp != NULL) { pclose(fp); } return buff; } int main(void) { char buff[1024]; memset(buff, 0, sizeof(buff)); printf("%s", shellcmd("ls", buff, sizeof(buff))); return 0; }
注意:C语言调用shell命令是新建一个进程执行的,执行速度很慢,最好不要C、Shell混合编程。
以上这篇C语言获取Shell返回结果的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
相关文章推荐
- android wifi 无线调试
- 如何组织构建多文件 C 语言程序(二)
- 运维入门
- 动态清空 nohup 输出文件
- install scrapy with pip and easy_install
- 如何写好 C main 函数
- Linux Shell常用技巧
- Shell 脚本编程陷阱
- shell字符串操作详解
- Lua和C语言的交互详解
- Shell中删除某些文件外所有文件的3个方法
- Ruby中执行Linux shell命令的六种方法详解
- VB使用shell函数打开外部exe程序的实现方法
- Shell编程的一些知识集合
- Shell中的for和while循环详细总结
- 什么是Shell?Shell脚本基础知识详细介绍
- Shell脚本中引用、调用另一个脚本文件的2种方法
- Shell脚本解压rpm软件包
- Linux Shell 数组建立及使用技巧
- Shell脚本实现复制文件到多台服务器的代码分享