Linux_Kernel PS 명령어 만들기

이재하·2023년 6월 10일
0

linux-kernel

목록 보기
1/3

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <fcntl.h>

int main() {
    // 무한 루프로 프로세스 정보를 지속적으로 출력
    while(1) {
        // /proc 디렉토리를 연다.
        DIR *dirp = opendir("/proc");
        struct dirent *dp;

        // 디렉토리를 열지 못했을 경우 에러 메시지 출력
        if (!dirp) {
            perror("opendir");
            return 1;
        }

        // 헤더 출력
        printf("PID\tTTY\tCMD\n");

        // /proc 디렉토리 내의 각 항목을 읽는다.
        while ((dp = readdir(dirp)) != NULL) {
            // 디렉토리 이름(문자열)을 정수로 변환 (프로세스 ID)
            int pid = atoi(dp->d_name); 

            // 변환된 값이 0보다 크면 프로세스 디렉토리로 간주
            if (pid > 0) {
                char cmd_path[256];
                char cmd[256];

                // cmdline 파일의 경로를 문자열로 만든다.
                snprintf(cmd_path, sizeof(cmd_path), "/proc/%d/cmdline", pid);

                // cmdline 파일을 열고 파일 디스크립터를 가져온다.
                int fd = open(cmd_path, O_RDONLY);
                
                // 파일을 열었으면
                if (fd >= 0) {
                    // cmdline 파일 내용을 읽는다.
                    ssize_t length = read(fd, cmd, sizeof(cmd) - 1);
                    
                    // 내용이 있으면
                    if (length > 0) {
                        // 문자열 끝에 널 문자를 추가
                        cmd[length] = '\0';

                        // 널 문자를 공백으로 변환 (cmdline 내용은 널 문자로 구분됨)
                        for (int i = 0; i < length; i++) {
                            if (cmd[i] == '\0') {
                                cmd[i] = ' ';
                            }
                        }

                        // 출력 (TTY는 예시로 pts/0, 실제로는 추가 로직 필요)
                        printf("%d\tpts/0\t%s\n", pid, cmd);
                    }
                    // 파일 디스크립터를 닫는다.
                    close(fd);
                }
            }
        }

        // 디렉토리를 닫는다.
        closedir(dirp);

        // 1초 동안 대기
        sleep(1);
        
        // 줄바꿈 출력 (다음 출력을 위해)
        printf("\n");
    }

    // 프로그램 정상 종료
    return 0;
}

0개의 댓글