从Linux程序中执行shell(程序、脚本)并获得输出结果(转)
来源:互联网 发布:淘宝女装海报 编辑:程序博客网 时间:2024/05/16 15:28
在学习unix编程的过程中,发现系统还提供了一个popen函数,可以非常简单的处理调用shell,其函数原型如下:
FILE *popen(const char *command, const char *type);
该函数的作用是创建一个管道,fork一个进程,然后执行shell,而shell的输出可以采用读取文件的方式获得。采用这种方法,既避免了创建临时文件,又不受输出字符数的限制,推荐使用。
popen使用FIFO管道执行外部程序。
#include <stdio.h>
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);
popen 通过type是r还是w确定command的输入/输出方向,r和w是相对command的管道而言的。r表示command从管道中读入,w表示 command通过管道输出到它的stdout,popen返回FIFO管道的文件流指针。pclose则用于使用结束后关闭这个指针。
下面看一个例子:
////getconsole.c
//
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define BUFLEN (1024)
int readconsole(char *cmd, char *buf, int buflen) {
FILE *stream;
int readlen;
stream = popen(cmd, "r" ); //将“ls -l”命令的输出 通过管道读取(“r”参数)到FILE* stream
readlen = fread( buf, sizeof(char), buflen, stream); //将刚刚FILE* stream的数据流读取到buf中
pclose( stream );
return readlen;
}
int main( void )
{
char buf[BUFLEN];
int readlen;
memset( buf, '\0', BUFLEN );//初始化buf,以免后面写如乱码到文件中
readlen = readconsole("ls", buf, BUFLEN);
printf("ls len=%d,buf=%s\n", readlen, buf);
return 0;
}
编译:
gcc -o getconsole ./getconsole.c
说明:这个是简略修改版本
原文出处:http://hi.baidu.com/tihu1111/blog/item/98e41c3d3a621ae23c6d9744.html
- 从Linux程序中执行shell(程序、脚本)并获得输出结果(转)
- 从Linux程序中执行shell(程序、脚本)并获得输出结果(转)
- 从Linux程序中执行shell(程序、脚本)并获得输出结果(转)
- 从Linux程序中执行shell(程序、脚本)并获得输出结果(转)
- 从Linux程序中执行shell(程序、脚本)并获得输出结果
- 从Linux程序中执行shell(程序、脚本)并获得输出结果
- 从Linux程序中执行shell(程序、脚本)并获得输出结果
- 从Linux程序中执行shell(程序、脚本)并获得输出结果
- 从Linux程序中执行shell(程序、脚本)并获得输出结果
- 从Linux程序中执行shell(程序、脚本)并获得输出结果
- 从Linux程序中执行shell(程序、脚本)并获得输出结果
- Linux程序中执行shell(程序、脚本)并获得输出结果
- 从Linux程序中执行shell(程序、脚本)并获得输出结果
- 从Linux程序中执行shell(程序、脚本)并获得输出结果
- linux 或WIN 程序中执行脚本获得输出结果
- Java代码中调用shell脚本和python脚本并获得输出结果(分为小数据量和大数据量)
- c程序中获得命令行输出结果
- linux的C程序 调用 shell脚本,获取shell的执行结果
- Cppcheck软件使用
- 如何看Dlink DWA-125 无线网卡使用的芯片
- ideveloper-开发者拥有自己免费的空间域名!
- Terracotta配置文件
- 网页跳转代码简介 301 302
- 从Linux程序中执行shell(程序、脚本)并获得输出结果(转)
- nagios安装步骤
- opencv 颜色直方图
- ApplicationContextAware
- 城市轨道综合监控跨屏组态问题研究
- ubuntu下无线网卡解决经历
- 网站命名规范大全:CSS规范便于交流
- iPhone开发资源PDF电子书
- 菜鸟程序员笔记