c程序-popen调用shell指令

一、popen和pclose函数介绍

文章 <Linux 笔记--system 函数执行shell指令>,介绍了 system 函数执行shell 指令。但是 system 函数只能获取到shell命令的返回值,而不能获取shell命令的输出结果。

这篇文章将介绍 popen 和 pclose 函数,通过调用 popen 函数来调用 shell 指令,可以获取shell命令的输出信息或者与执行的指令进行交互。 

看下 popen 函数介绍:

The  popen()  function opens a process by creating a pipe, forking, and invoking the shell.  

函数头文件:

#include <stdio.h>

函数原型:

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


int pclose(FILE *stream);

描述:

The  popen()  function opens a process by creating a pipe, forking, and
invoking the shell.  Since a pipe is by definition unidirectional,  the
type  argument  may  specify  only  reading  or  writing, not both; the
resulting stream is correspondingly read-only or write-only.

二、测试代码

popen 和 pclose 需成对使用。popen 第二个参数为 "r" 和 "w"

功能 使用 ifconfig 指令获取返回的网卡信息并打印,测试代码如下:

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


int main(int argc,char*argv[])
{  
    FILE *fstream=NULL;    
    char buff[1024];  
    memset(buff,0,sizeof(buff));  
    if(NULL==(fstream=popen("ifconfig","r"))) // ifconfig 指令   
    {   
            fprintf(stderr,"execute command failed: %s",strerror(perror));    
            return -1;    
    }   
    printf("%s\r\n","haha-start");  
    while(NULL!=fgets(buff, sizeof(buff), fstream)) // 获取 ifconfig 指令返回的数据信息
    {
            printf("%s",buff);  
    }
    printf("%s\r\n","haha-end");  
    pclose(fstream);  // 关闭
    return 0;   
}

三、测试结果

编译执行,测试结果如下:

c18bbf13ef69df9c0ac6b015f4895742.png

可以看到执行了 ifconfig 指令,并且正确获取到了返回数据结果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值