Pregunta

Acabo de escribir la siguiente función de C++ a través de programación determinar la cantidad de RAM que el sistema se ha instalado.Funciona, pero a mí me parece que debe haber una manera más simple de hacer esto.Alguien puede decirme si me falta algo?

getRAM()
{
    FILE* stream = popen( "head -n1 /proc/meminfo", "r" );
    std::ostringstream output;
    int bufsize = 128;

    while( !feof( stream ) && !ferror( stream ))
    {
        char buf[bufsize];
        int bytesRead = fread( buf, 1, bufsize, stream );
        output.write( buf, bytesRead );
    }
    std::string result = output.str();

    std::string label, ram;
    std::istringstream iss(result);
    iss >> label;
    iss >> ram;

    return ram;
}

En primer lugar, estoy usando popen("head -n1 /proc/meminfo") para obtener la primera línea de la meminfo archivo desde el sistema.El resultado de ese comando se parece a

MemTotal:775280 kB

Una vez que tengo esa salida en un istringstream, es muy simple para convertir a obtener la información que yo quiero.Mi pregunta es, hay una manera más simple de leer en la salida de este comando?Hay una biblioteca estándar de C++ llamada para leer en la cantidad de RAM del sistema?

¿Fue útil?

Solución

En Linux, puede utilizar la función sysinfo que establece los valores de la siguiente estructura:

   #include <sys/sysinfo.h>

   int sysinfo(struct sysinfo *info);

   struct sysinfo {
       long uptime;             /* Seconds since boot */
       unsigned long loads[3];  /* 1, 5, and 15 minute load averages */
       unsigned long totalram;  /* Total usable main memory size */
       unsigned long freeram;   /* Available memory size */
       unsigned long sharedram; /* Amount of shared memory */
       unsigned long bufferram; /* Memory used by buffers */
       unsigned long totalswap; /* Total swap space size */
       unsigned long freeswap;  /* swap space still available */
       unsigned short procs;    /* Number of current processes */
       unsigned long totalhigh; /* Total high memory size */
       unsigned long freehigh;  /* Available high memory size */
       unsigned int mem_unit;   /* Memory unit size in bytes */
       char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding for libc5 */
   };

Si quieres hacerlo únicamente mediante las funciones de C++ (yo me quedaría con sysinfo), yo recomiendo tomar un enfoque utilizando C++ std::ifstream y std::string:

unsigned long get_mem_total() {
    std::string token;
    std::ifstream file("/proc/meminfo");
    while(file >> token) {
        if(token == "MemTotal:") {
            unsigned long mem;
            if(file >> mem) {
                return mem;
            } else {
                return 0;       
            }
        }
        // ignore rest of the line
        file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    return 0; // nothing found
}

Otros consejos

No es necesario usar popen(), solo puede leer el archivo usted mismo. Además, si la primera línea no es lo que está buscando, fallará, ya que head -n1 solo lee la primera línea y luego sale. No estoy seguro de por qué está mezclando E / S C y C ++ así; está perfectamente bien, pero probablemente debería optar por ir a C o C ++. Probablemente lo haría algo como esto:

int GetRamInKB(void)
{
    FILE *meminfo = fopen("/proc/meminfo", "r");
    if(meminfo == NULL)
        ... // handle error

    char line[256];
    while(fgets(line, sizeof(line), meminfo))
    {
        int ram;
        if(sscanf(line, "MemTotal: %d kB", &ram) == 1)
        {
            fclose(meminfo);
            return ram;
        }
    }

    // If we got here, then we couldn't find the proper line in the meminfo file:
    // do something appropriate like return an error code, throw an exception, etc.
    fclose(meminfo);
    return -1;
}

Recuerde / proc / meminfo es solo un archivo. Abra el archivo, lea la primera línea, cierre el archivo. ¡Voil & # 225 ;!

Incluso top (de procps) analiza /proc/meminfo, vea aquí .

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top