C++에서 Linux 시스템 RAM의 양을 어떻게 결정합니까?
문제
시스템에 설치된 RAM의 양을 프로그래밍 방식으로 확인하기 위해 다음 C++ 함수를 작성했습니다.작동하지만 이 작업을 수행하는 더 간단한 방법이 있어야 할 것 같습니다.누군가 내가 뭔가를 놓치고 있는지 말해 줄 수 있습니까?
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;
}
먼저, 제가 사용하고 있는 popen("head -n1 /proc/meminfo")
시스템에서 meminfo 파일의 첫 번째 줄을 가져옵니다.해당 명령의 출력은 다음과 같습니다.
메모리 합계:775280KB
일단 그 출력을 얻었으면 istringstream
, 내가 원하는 정보를 얻기 위해 토큰화하는 것은 간단합니다.제 질문은 이 명령의 출력을 읽는 더 간단한 방법이 있습니까?입니다.시스템 RAM의 양을 읽는 표준 C++ 라이브러리 호출이 있습니까?
해결책
Linux에서는 다음 기능을 사용할 수 있습니다. sysinfo
다음 구조체에 값을 설정합니다.
#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 */
};
C++의 기능만을 사용하여 수행하고 싶다면 (나는 다음을 고수할 것입니다.) sysinfo
), 다음을 사용하여 C++ 접근 방식을 취하는 것이 좋습니다. std::ifstream
그리고 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
}
다른 팁
사용할 필요가 없습니다 popen()
, 파일을 직접 읽을 수 있습니다.또한 첫 번째 줄에 원하는 내용이 없으면 실패하게 됩니다. head -n1
첫 번째 줄만 읽고 종료합니다.왜 C와 C++ I/O를 그렇게 혼합하는지 잘 모르겠습니다.완전히 괜찮습니다. 하지만 아마도 모두 C로 선택하거나 모두 C++로 선택해야 할 것입니다.나는 아마도 다음과 같이 할 것입니다 :
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;
}
/proc/meminfo는 단지 파일이라는 것을 기억하세요.파일을 열고, 첫 번째 줄을 읽고, 파일을 닫습니다.짜잔!
심지어 top
(에서 procps
) 구문 분석 /proc/meminfo
, 보다 여기.