728x90
프로세스의 메모리의 관리하기 위해선, 먼저 현재 실행 중인 프로세스 목록을 알아야한다.
리눅스에서는 현재 실행중인 프로세스들의 정보가 /proc 디렉토리에 저장된다.
/proc 디렉토리에는 숫자로 된 이름의 디렉토리가 존재하는데, 이는 각각의 PID를 의미한다.
예를 들어, /proc/2456은 PID가 2456인 프로세스에 대한 정보를 담고있다.
struct dirent { /* when _DARWIN_FEATURE_64_BIT_INODE is NOT defined */
ino_t d_ino; /* file number of entry */
__uint16_t d_reclen; /* length of this record */
__uint8_t d_type; /* file type, see below */
__uint8_t d_namlen; /* length of string in d_name */
char d_name[255 + 1]; /* name must be no longer than this */
};
(dirent 구조체 필드)
/*
* File types
*/
#define DT_UNKNOWN 0
#define DT_FIFO 1
#define DT_CHR 2
#define DT_DIR 4
#define DT_BLK 6
#define DT_REG 8
#define DT_LNK 10
#define DT_SOCK 12
#define DT_WHT 14
디렉토리 타입은 DT_DIR로 확인한다.
즉, /proc을 순회하면서, 디렉토리 타입이 DT_DIR인 항목 중에서,
d_name(디렉토리 이름)이 숫자로만 이루어진 항목을 atoi로 정수형 PID로 변환하여 출력하면 된다.
#include <stdio.h>
#include <stdlib.h>
#include <sys/ptrace.h>
#include <dirent.h>
#include <sys/types.h>
#include <unistd.h>
void monitor_all_process()
{
DIR *dir = opendir("/proc"); //proc dir열고
if(dir == NULL)
{
perror("opendir error");
exit(1);
}
struct dirent *all_process;
while((all_process = readdir(dir)) != NULL) //proc dir 순회
{
if(all_process->d_type == DT_DIR) //DT_DIR이면 즉, 디렉토리면
{
pid_t pid = atoi(all_process->d_name); //정수형으로 바꾸고
if(pid > 0)
{
printf("[Monitor] PID : %d\n", pid); //출력
}
}
}
closedir(dir);
}
int main()
{
while(1)
{
system("clear");
monitor_all_process();
sleep(1);
}
return 0;
}
일단 프로세스 목록을 출력하는 것 까지는 했고,
이 코드에서 프로세스 목록 데이터를 다른 코드로 전달하는 부분은 다시 수정해서 작성해야할 듯 하다.
(하지만, 프로세스 정보가 /proc디렉토리에 전달되는거는 linux한정이다..
즉, 윈도우, mac에서는 이 방식으로 프로세스 정보를 가져올 수 없다.)
728x90
'C프로그래밍 > MemoryTracker' 카테고리의 다른 글
RealtimeMemTracker - 4, ARM64 Linux에서 PTRACE_SYSCALL을 사용한 시스템 콜 트레이싱 (0) | 2025.03.25 |
---|---|
RealtimeMemTracker - 3, 시스템콜 번호 확인하기 (1) | 2025.03.23 |
RealtimeMemTracker - 1, 다른 프로세스의 SystemCall 추적하기 (0) | 2025.03.20 |