Search code examples
c++linuxdistribution

C++ get linux distribution name\version


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

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().


Solution

  • 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;
    }