管道popen


//----------------------------------------------------

//AUTHOR: lanyang123456

//DATE: 2014-10-27

//---------------------------------------------------



#include <stdio.h>
#include <string.h>

#include <string>

using namespace std;

int cmd_exec(const char *cmd, string &strRet)
{
	if (cmd == NULL)
	{
		return -1;
	}

	FILE *pStream = popen(cmd, "r");
	if (pStream == NULL)
	{
        	perror("popen failed.");
        	return -1;
	}

	char buf[128]={0};
	while (fgets(buf, sizeof(buf)-1, pStream) != NULL)
	{
		strRet.append(buf);
		memset(buf, 0, 128);
	}

	if (pclose(pStream) < 0) {
		perror("pclose failed.");
		return -1;
	}
	return 0;
}


int main()
{
	int nRet;
	char cmd[512];
	const char *interface = "eth0";
   	string strIfconfig;
    	memset(cmd, 0, 512);
   	sprintf(cmd, "ifconfig %s", interface);
    	nRet = cmd_exec(cmd, strIfconfig);
	if (nRet == -1) {
		perror("cmd_exec error");
		return -1;
	}

	if (strIfconfig.empty())
	{
		printf("can't get eth0 info.\n");
		return -1;
	}
	printf("ifconfig info:\n");
	printf("%s", strIfconfig.c_str());
	return 0;
}

$ g++ -o test popen.cpp
$ ./test
ifconfig info:
eth0      Link encap:Ethernet  HWaddr AA:BB:CC:DD:EE:FF 
          inet addr:192.168.1.116  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: abcd::efgh:1cff:feec:ff21/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:29168 errors:0 dropped:0 overruns:0 frame:0
          TX packets:3508 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:6110024 (6.1 MB)  TX bytes:540844 (540.8 KB)
          Interrupt:20 Memory:f7c00000-f7c20000




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值