天天看點

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