使用popen函數創建ping命令管道

首先介紹下popen函數。

頭文件:

#include <stdio.h>

函數定義:

FILE *popen(const char *command, const char*type);

關聯函數:

int pclose(FILE *stream);

popen() 函數創建一個管道 ,調用fork建立一個 進程, 並調用shell。因爲該函數的返回值是一個普通的標準I/0流,所以它只能用pclose()函數來關閉。

command 參數 是 一個 字符串指針, 指向的是一個 以 null 結束符 結尾的字符串, 這個字符串包含 一個 shell 命令. 這個命令 被送到 /bin/sh 以 -c 參數 執行, 即由 shell 來執行.

type 參數 也是 一個 指向 以 null 結束符結尾的 字符串的指針, 這個字符串 必須是'r' 或者'w’ 來指明 是 讀還是寫. 因爲 管道是被定義成單向的, 所以type 參數 只能定義成 只讀或者 只寫, 不能是 兩者同時, 結果流也相應的 是隻讀 或者 只寫.

注意,popen 函數的 輸出流默認是被全緩衝的.

pclose 函數 等待 相關的進程結束並返回 一個 command 命令的 退出狀態.

好了下面根據以上說明作成ping命令管道,如下所示:

#include <stdio.h>  
#include <stdlib.h>  

#define REMOTEIP "192.168.100.11"

int main( )
{
	char   psBuffer[512];
	FILE   *pPing;

	pPing = popen( "ping " REMOTEIP, "r" );
	if( pPing == NULL ){
		printf("error end\n");
		exit( 1 );
	}

	while(fgets(psBuffer, 512, pPing))
	{
		printf("%s", psBuffer);
	}

	pclose(pPing);
}

編譯運行如下:

[root@xxx ping]# gcc ping.c 
[root@xxx ping]# ./a.out 
PING 192.168.100.11 (192.168.100.11) 56(84) bytes of data.
64 bytes from 192.168.100.11: icmp_seq=1 ttl=64 time=2.19 ms
64 bytes from 192.168.100.11: icmp_seq=2 ttl=64 time=0.352 ms
64 bytes from 192.168.100.11: icmp_seq=3 ttl=64 time=0.322 ms
64 bytes from 192.168.100.11: icmp_seq=4 ttl=64 time=0.305 ms
^C
[root@ xxx -vm ping]#



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章