zoukankan      html  css  js  c++  java
  • 能够返回运行结果的system函数加强版本号

    /*********************************************************************
     * Author  : Samson
     * Date    : 03/13/2015
     * Test platform:
     *              3.13.0-24-generic
     *              GNU bash, 4.3.11(1)-release 
     * *******************************************************************/

    在GNU Linux C编程中,要想进行系统命令的运行的话,仅仅提供了system接口,可是此接口并不能得到命令运行后所输出的值。而仅仅可以得到命令是否运行成功的结果。仅仅这种功能还是不够的。有的时候是要必须通过命令的输出来推断下一步的结果或步骤的,那么怎么样可以得到system命令运行的结果呢?那就行使用到popen函数和fgets函数进行命令的输出信息的获取了,实际样例例如以下:

    注意:此接口仅仅可以获取命令输出的最后一行的信息。若有多行输出信息将不可以所有获取到,此封装接口仅仅适用于得到命令运行结果的最后一行的信息。



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

    int super_system(const char * cmd, char *retmsg, int msg_len)
    {
            FILE * fp;
            int res = -1;
            if (cmd == NULL || retmsg == NULL || msg_len < 0)
            {
                    printf("Err: Fuc:%s system paramer invalid! ", __func__);
                    return 1;
            }
            if ((fp = popen(cmd, "r") ) == NULL)
            {
                    perror("popen");
                    printf("Err: Fuc:%s popen error: %s ", __func__, strerror(errno));
                    return 2;
            }
            else
            {
                    memset(retmsg, 0, msg_len);
                    while(fgets(retmsg, msg_len, fp));
                    {
                            printf("Fuc: %s fgets buf is %s ", __func__, retmsg);
                    }
                    if ( (res = pclose(fp)) == -1)
                    {
                            printf("Fuc:%s close popen file pointer fp error! ", __func__);
                            return 3;
                    }
                    //drop #012 from system result retmsg.
                    retmsg[strlen(retmsg)-1] = '';
                    return 0;
            }
    }

    int main()
    {
        char *cmd = "whoami";
        char *cmd1 = "initctl list";
        char retmsg[1024] = {0};
        int ret = 0;
        ret  = super_system(cmd, retmsg, sizeof(retmsg));
        printf("system ret is %d retmsg is %s ", ret, retmsg);
        return 0;
    }

    main函数中使用了whoami的命令,运行结果即是当前username。


    运行结果:
    ufo@ufo:~$ ./a.out
    Fuc: super_system fgets buf is ufo

    system ret is 0 retmsg is
    ufo

  • 相关阅读:
    贾庆山老师对研究生做学术的几点建议
    normalization flow
    PP: Robust Anomaly Detection for Multivariate Time Series through Stochastic Recurrent Neural Network
    PP: Multi-Horizon Time Series Forecasting with Temporal Attention Learning
    Attention machenism
    PP: Modeling extreme events in time series prediction
    Learn from Niu 2020.1.28
    Big research problems (1)
    PP: UMAP: uniform manifold approximation and projection for dimension reduction
    Dimension reduction
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/5147776.html
Copyright © 2011-2022 走看看