C、Shell混合编程小技巧


写在前面:

开始工作的前两年一直都是在Windows平台下,使用的编程方式多是单一语言,全部使用C++,或全部使用C#,或者java等等等。

在最近换了工作,投奔互联网之后,开发平台彻底转移到Linux平台,告别了Win7,用上了mac,哈哈。

言归正传:

int system(const char *);

Linux c 中的system函数的作用是在程序中调用shell。我的小技巧的思路就是将system函数的执行结果读取回来。返回的结果是字符串,不要小瞧这个字符串,经过巧妙的设计,该技巧可以帮助我做很多很奇妙的事情。

例如:我在程序中的关于配置信息读取的部分就都是写在python文件中,当我需要读取配置的时候,我会去执行python脚本来得到我需要的结果。这么做的好处之一就是写在python文件中的数据结构可以自己随意按需求定义,而不是拘泥于传统的ini、json、xml的定义方式。

代码:

int main(int argc, char **argv)
{
    char result[1025];
    my_system("ls -al", result, 1025);
    printf("the result is\n\n%s\n", result);
 
    return 0;
}
 
int my_system(const char* pCmd, char* pResult, int size)
{
    int fd[2];
    int pid;
    int count;
    int left;
    char* p = 0;
    int maxlen = size - 1;
    memset(pResult, 0, size);
    if(pipe(fd)){
        printf("pipe errorn");
        return -1;
    }
    if((pid = fork()) == 0)
    {// chile process
        int fd2[2];
        if(pipe(fd2)){
            printf("pipe2 errorn");
            return -1;
        }
        close(1);
        dup2(fd2[1],1);
        close(fd[0]);
        close(fd2[1]);
        system(pCmd);
        read(fd2[0], pResult, maxlen);
        pResult[strlen(pResult)-1] = 0;
        write(fd[1], pResult, strlen(pResult));
        close(fd2[0]);
        exit(0);
    }
    // parent process
    close(fd[1]);
    p = pResult;
    left = maxlen;
    while((count = read(fd[0], p, left))) {
        p += count;
        left -= count;
        if(left == 0)
        break;
    }
    close(fd[0]);
    return 0;
}

本文永久更新链接地址:

相关内容