C语言调用shell命令方法
2016-02-18 15:16
435 查看
在C语言中执行shell命令的方法:
1. system(shell_string);
该方法无法返回shell命令的输出结果,只能返回返回值。
2. popen/fgets/fputs/pclose
该方法可以读取shell命令的输出结果和返回值,也可以向shell命令输入参数。
使用方法:(参考http://baike.baidu.com/view/2445803.htm)
说明:
popen() 函数通过创建一个管道,调用 fork 产生一个子进程,执行一个 shell 以运行命令来开启一个进程。这个进程必须由 pclose() 函数关闭,而不是 fclose() 函数。pclose() 函数关闭标准 I/O 流,等待命令执行结束,然后返回
shell 的终止状态。如果 shell 不能被执行,则 pclose() 返回的终止状态与 shell 已执行 exit 一样。
type 参数只能是读或者写中的一种,得到的返回值(标准 I/O 流)也具有和 type 相应的只读或只写类型。如果 type 是 "r" 则文件指针连接到 command 的标准输出;如果 type 是 "w" 则文件指针连接到 command 的标准输入。
command 参数是一个指向以 NULL 结束的 shell 命令字符串的指针。这行命令将被传到 bin/sh 并使用-c 标志,shell 将执行这个命令。
popen 的返回值是个标准 I/O 流,必须由 pclose 来终止。前面提到这个流是单向的。所以向这个流写内容相当于写入该命令的标准输入;命令的标准输出和调用 popen 的进程相同。与之相反的,从流中读数据相当于读取命令的标准输出;命令的标准输入和调用 popen 的进程相同。
返回值:
如果调用 fork() 或 pipe() 失败,或者不能分配内存将返回NULL,否则返回标准 I/O 流。
popen 没有为内存分配失败设置 errno 值。
如果调用 fork() 或 pipe() 时出现错误,errno 被设为相应的错误类型。
如果 type 参数不合法,errno将返回EINVAL。
使用范例:
popen.c
popen_sh.sh
1. system(shell_string);
该方法无法返回shell命令的输出结果,只能返回返回值。
2. popen/fgets/fputs/pclose
该方法可以读取shell命令的输出结果和返回值,也可以向shell命令输入参数。
使用方法:(参考http://baike.baidu.com/view/2445803.htm)
#include <stdio.h> 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 一样。
type 参数只能是读或者写中的一种,得到的返回值(标准 I/O 流)也具有和 type 相应的只读或只写类型。如果 type 是 "r" 则文件指针连接到 command 的标准输出;如果 type 是 "w" 则文件指针连接到 command 的标准输入。
command 参数是一个指向以 NULL 结束的 shell 命令字符串的指针。这行命令将被传到 bin/sh 并使用-c 标志,shell 将执行这个命令。
popen 的返回值是个标准 I/O 流,必须由 pclose 来终止。前面提到这个流是单向的。所以向这个流写内容相当于写入该命令的标准输入;命令的标准输出和调用 popen 的进程相同。与之相反的,从流中读数据相当于读取命令的标准输出;命令的标准输入和调用 popen 的进程相同。
返回值:
如果调用 fork() 或 pipe() 失败,或者不能分配内存将返回NULL,否则返回标准 I/O 流。
popen 没有为内存分配失败设置 errno 值。
如果调用 fork() 或 pipe() 时出现错误,errno 被设为相应的错误类型。
如果 type 参数不合法,errno将返回EINVAL。
使用范例:
popen.c
#include <stdio.h> void main() { char buf[100]; FILE *fd; //test read from shell fd = popen("pwd", "r"); if(fd) { fgets(buf, sizeof(buf), fd); pclose(fd); printf("buf=%s.\n", buf); } //test write to shell fd = popen("./popen_sh.sh", "w"); if(fd) { fputs("iiiiiiiiiiiiiiii", fd); pclose(fd); } }
popen_sh.sh
#!/bin/sh echo "Please enter string:" read input_string echo "input_string=$input_string" exit 12
相关文章推荐
- shell脚本:批量修改文件名(文件名中添加字符)
- python中执行shell命令的几个方法
- linux中的shell 进程
- shell脚本个人总结
- shell 基本计算、逻辑运算、位运算详解
- zabbix自动发现结合shell实现自动发现占用内存最大top10进程并监控其资源
- 运维常用shell脚本
- 日志/数据自动压缩备份删除小脚本
- .bash_profile和.bashrc的区别(如何设置生效)
- Shell脚本,包含了[分支 循环 数组 搜索 运算等基本功能]
- 转 Jmeter之Bean shell使用(二)
- 转 Jmeter之Bean shell使用(一)
- Shell输入输出重定向
- shell脚本实现从某一行开始附加内容
- atitit.bsh BeanShell 的动态脚本使用java
- atitit.bsh BeanShell 的动态脚本使用java
- atitit.bsh BeanShell 的动态脚本使用java
- shell---dialog
- 定制自己的shell
- Windows使用SSH Secure Shell实现免密码登录Linux的方法以及使用scp2命令免密码下载文件