linux popen函数简单实例
2016-01-30 09:58
741 查看
Linux 中的popen机制可以在程序中执行一个shell命令,有两种操作模式,分别为读和写。在读模式中,程序中可以读取到命令的输出,其中有一个应用就是获取网络接口的参数。在写模式中,最常用的是创建一个新的文件或开启其他服务等。
运行后结果:
eth0 Link encap:Ethernet HWaddr 00:0c:29:db:ac:05
inet6 addr: fe80::20c:29ff:fedb:ac05/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:306065 errors:1 dropped:0 overruns:0 frame:0
TX packets:291821 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:130350798 (130.3 MB) TX bytes:119043669 (119.0 MB)
Interrupt:19 Base address:0x2000
CMD: ls
test.tmp
<span style="font-size:18px;">#include <stdlib.h> #include <stdio.h> #define BUF_SIZE 1024 char buf[BUF_SIZE]; int main(void) { FILE * p_file = NULL; p_file = popen("ifconfig eth0", "r"); if (!p_file) { fprintf(stderr, "Erro to popen"); } while (fgets(buf, BUF_SIZE, p_file) != NULL) { fprintf(stdout, "%s", buf); } pclose(p_file); p_file = popen("touch test.tmp", "w"); if (!p_file) { fprintf(stderr, "Erro to popen"); } while (fgets(buf, BUF_SIZE, p_file) != NULL) { fprintf(stdout, "%s", buf); } pclose(p_file); p_file = popen("touch test.tmp", "w"); if (!p_file) { fprintf(stderr, "Erro to popen"); } pclose(p_file); return 0; } </span>
运行后结果:
eth0 Link encap:Ethernet HWaddr 00:0c:29:db:ac:05
inet6 addr: fe80::20c:29ff:fedb:ac05/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:306065 errors:1 dropped:0 overruns:0 frame:0
TX packets:291821 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:130350798 (130.3 MB) TX bytes:119043669 (119.0 MB)
Interrupt:19 Base address:0x2000
CMD: ls
test.tmp
相关文章推荐
- Linux:fping主机扫描
- Linux下常用命令总结
- linux 好玩的命令
- Linux 底行模式常用命令
- Linux acpi off学习
- kernel的initcall函数
- linux上R语言源码安装
- Installing CUDA Toolkit 7.5 on Ubuntu 14.04 Linux
- CentOS7搭建SVN服务器
- linux-->ldd命令的介绍
- Centos7安装Qt5.5
- linux信号-------初涉
- 在CentOS VPS上源码安装高版本git
- 2016-1-29 linux基础学习3
- 阿 里云Centos 6.5安装laravel 5.1 配置一
- kali linux karmetasploit配置【续】
- kali linux karmetasploit配置
- redhat使用centosYUM源
- VMware on Linux(Centos6.6)
- VMware中centos安装kvm