C程序获取shell脚本命令输出,使用popen()函数
2012-07-11 20:07
896 查看
C程序如果想要调用shell脚本,并获得脚本执行的结果,可以使用popen()函数。
定义:
FILE * popen(const char * command, const char * type);
int pclose(FILE * stream);
原理:
popen() 函数通过创建一个管道,调用 fork 产生一个子进程,执行一个 shell 以运行命令来开启一个进程。这个进程必须由 pclose() 函数关闭,而不是 fclose() 函数。pclose() 函数关闭标准 I/O 流,等待命令执行结束,然后返回 shell 的终止状态。如果 shell 不能被执行,则 pclose()
返回的终止状态与 shell 已执行 exit 一样。
SAMPLE:
参考:
http://www.360doc.com/content/11/1120/21/4910_166050382.shtml
http://www.lainoox.com/how-to-execute-shell-commands-c/
定义:
FILE * popen(const char * command, const char * type);
int pclose(FILE * stream);
原理:
popen() 函数通过创建一个管道,调用 fork 产生一个子进程,执行一个 shell 以运行命令来开启一个进程。这个进程必须由 pclose() 函数关闭,而不是 fclose() 函数。pclose() 函数关闭标准 I/O 流,等待命令执行结束,然后返回 shell 的终止状态。如果 shell 不能被执行,则 pclose()
返回的终止状态与 shell 已执行 exit 一样。
SAMPLE:
#include <stdio.h> int main() { FILE *fp; char line[256]; fp = popen("ping 127.0.0.1", "r"); if(fp == NULL) { printf("error!\n"); return -1; } while(!feof(fp)) { if(fgets(line, 256, fp) != NULL) printf("%s", line); } pclose(fp); return 0; }
参考:
http://www.360doc.com/content/11/1120/21/4910_166050382.shtml
http://www.lainoox.com/how-to-execute-shell-commands-c/
相关文章推荐
- shell 脚本之获取命令输出字符串以及函数参数传递
- linux C程序中获取shell脚本输出(如获取system命令输出)
- popen——C程序中获取Shell命令的输出
- inux C程序中获取shell脚本输出(如获取system命令输出)
- linux C程序中获取shell脚本输出(如获取system命令输出)
- linux C程序中获取shell脚本输出(如获取system命令输出)
- linux C程序中获取shell脚本输出(如获取system命令输出)
- popen——C程序中获取Shell命令的输出
- 转载_popen——C程序中获取Shell命令的输出
- shell 脚本之获取命令输出字符串以及函数参数传递
- linux C程序中获取shell脚本输出(如获取system命令输出)
- linux C程序中获取shell脚本输出(如获取system命令输出)
- linux C程序中获取shell脚本输出
- linux c程序中获取shell脚本输出
- linux c程序中获取shell脚本输出的实现方法
- C程序调用shell脚本共有三种方式:system()、popen()、exec系列函数
- Shell编程中的用户输入处理(4):在shell脚本中,使用read命令获取命令行输入
- linux C程序中获取shell脚本输出
- linux c程序中获取shell脚本输出 [转]
- 在C程序中使用popen调用shell脚本程序