管道popen

来源:互联网 发布:c语言exit语句 编辑:程序博客网 时间:2024/05/09 09:17


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

//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
原创粉丝点击