unix进程管道

unix建立进程 管道

最近在要在路由器新加入一个application, 主要做用是 自动切换operation mode.python

在流程中有一项要测试dns解析是否正常, 固然bash自己就有ping command, 可是有集成到c语言之中,就须要shell

使用进程管道, 我大体看了一下, 功能还不错, 下面介绍一下popen和 pclosebash

#include <stdio.h>

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

int pclose(FILE *fp);

针对函数介绍几点: 1.popen首先fork一个子进程, 子进程之中调用exec执行 cmdsting命令, 而且返回一个标准IO文件指针,网络

2.若是type为"r",则指针链接到cmdstring 命令的标准输出, 即cmdsting命令的输出返回到该指针,能够从该文件指针读出cmdstring的命令.app

3.若是typr为"w",则指针链接到cmdstring 命令的标准输入, 便可以向文件指针之中写入信息,给予子进程的标准输入.dom

4.子进程cmdstring命令由bash执行, 同时以sh -c cmdstring的形式执行, 意味着shell能够扩展cmdstring的任意字符. exp: ls *.c ; cmd 2>&1函数

5.和system同样, pclose也返回shell的终止状态, 若是shell不能执行, pclose的终止状态与shell的终止状态exit(127)的终止状态相同.工具

同时给我一个视例代码: 主要是ping命令的C封装, 测试domain name 或者 ip adderss可否访问, 同时也能够验证dns.测试

int ping_test(char *adderss, int count){
    FILE *fp;
    char buf[128];
    int ping_try, ping_success;
    sprintf(buf, "ping %s -w %d | grep \"packets received\", address, count);
    fp = popen(buf, "r");
    if(NULL == fp){
        return -1;
    }
    if(NULL == fgets(buf, sizeof(buf), fp)){
        pclose(fp);
        return -1;
    }
    pclose(fp);
    sscanf(buf, "%d packets transmitted, %d packets received", &ping_try, &ping_success);
    return ping_success;
}

同时在路由器中, 进程, 网络等信息都在/proc文件系统中能够访问到, 这给其余程序查看信息提供了方便. shell中有许多查看信息的工具, 相似cat grep ifconfig 等命令能够获得信息, 再使用进程管道就能够 在C程序中使用, 现给出部分通用程序代码:.net

#include <stdio.h>
    #include <unistd.h>
    int get_shell_info(char *return_info, char *cmd){
        FILE *fp;
        fp = popen(cmd_buf, "r");
        if(NULL == fp){
            return -1;
        }
        if(NULL == fgets(return_info, strlen(return_info), fp)){
            pclose(fp);
            return -1;
        }
        pclose(fp);  
        return 1;
           
    }

关于程序须要注意的几点

  1. return_info的size是多少, 要编写程序这本身估算, return_info不能太小, 否则会发生信息丢失的状况.
  2. 程序只是获得了shell程序的输出, 并无分析数据, 这部分须要本身实现.

程序使用:

#include <stdio.h>
#include <unistd.h>

#define COMMAND "ifconfig eth1 | grep inet"

int main(int argc, char **argv){
    char info[500];
    if(get_shell_info(info, COMMAND) > 0){
        .....
    }
}

刚才又看了看python的subprocess.Popen, 感受封装的蛮好, 文章地址

相关文章
相关标签/搜索