linux popen函数实现,linux popen函数简单实例

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

#include #include #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;

}

运行后结果:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值