Linux 中的popen机制可以在程序中执行一个shell命令,有两种操作模式,分别为读和写。在读模式中,程序中可以读取到命令的输出,其中有一个应用就是获取网络接口的参数。在写模式中,最常用的是创建一个新的文件或开启其他服务等。
<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