使用popen函数创建ping命令管道

来源:互联网 发布:上海行知学院怎么样 编辑:程序博客网 时间:2024/05/18 00:12

首先介绍下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 ms64 bytes from 192.168.100.11: icmp_seq=2 ttl=64 time=0.352 ms64 bytes from 192.168.100.11: icmp_seq=3 ttl=64 time=0.322 ms64 bytes from 192.168.100.11: icmp_seq=4 ttl=64 time=0.305 ms^C[root@ xxx -vm ping]#



0 0