C ++获取Linux发行版名称\版本 [英] C++ get linux distribution name\version

查看:136
本文介绍了C ++获取Linux发行版名称\版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据问题"如何获取Linux发行版名称和版本?,获取linux发行版的名称和版本,可以正常工作:

According to the question " How to get Linux distribution name and version? ", to get the linux distro name and version, this works:

lsb_release -a

在我的系统上,它显示所需的输出:

On my system, it shows the needed output:

No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 9.10
Release:    9.10
Codename:   karmic

现在,要在C ++中获取此信息,Qt4的QProcess将是一个不错的选择,但是由于我没有使用std c ++进行Qt开发,所以我需要知道如何在标准C ++中获取此信息,即过程的标准输出,以及解析信息的方法.

Now, to get this info in C++, Qt4's QProcess would be a great option but since I am developing without Qt using std c++, I need to know how to get this info in standard C++, i.e. the stdout of the process, and also a way to parse the info.

直到现在,我一直在尝试使用这里,但停留在函数阅读().

Uptil now I am trying to use code from here but am stuck on function read().

推荐答案

从cplusplus.com论坛获得它,只需调用GetSystemOutput("/usr/bin/lsb_release -a")即可.

Got it from cplusplus.com forums, a simple call GetSystemOutput("/usr/bin/lsb_release -a") works.

char* GetSystemOutput(char* cmd){
        int buff_size = 32;
    char* buff = new char[buff_size];

        char* ret = NULL;
        string str = "";

    int fd[2];
    int old_fd[3];
    pipe(fd);


        old_fd[0] = dup(STDIN_FILENO);
        old_fd[1] = dup(STDOUT_FILENO);
        old_fd[2] = dup(STDERR_FILENO);

        int pid = fork();
        switch(pid){
                case 0:
                        close(fd[0]);
                        close(STDOUT_FILENO);
                        close(STDERR_FILENO);
                        dup2(fd[1], STDOUT_FILENO);
                        dup2(fd[1], STDERR_FILENO);
                        system(cmd);
                        //execlp((const char*)cmd, cmd,0);
                        close (fd[1]);
                        exit(0);
                        break;
                case -1:
                        cerr << "GetSystemOutput/fork() error\n" << endl;
                        exit(1);
                default:
                        close(fd[1]);
                        dup2(fd[0], STDIN_FILENO);

                        int rc = 1;
                        while (rc > 0){
                                rc = read(fd[0], buff, buff_size);
                                str.append(buff, rc);
                                //memset(buff, 0, buff_size);
                        }

                        ret = new char [strlen((char*)str.c_str())];

                        strcpy(ret, (char*)str.c_str());

                        waitpid(pid, NULL, 0);
                        close(fd[0]);
        }

        dup2(STDIN_FILENO, old_fd[0]);
        dup2(STDOUT_FILENO, old_fd[1]);
        dup2(STDERR_FILENO, old_fd[2]);

    return ret;
}

这篇关于C ++获取Linux发行版名称\版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆