Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

Java 9의 Process API로 프로세스 트리를 탐색하는 방법

Java 9에서는 Process API가 크게 개선되어 운영체제(OS) 프로세스를 손쉽게 관리하고 제어할 수 있게 되었습니다. Java 9 이전에는 자바 프로그램만으로 운영체제 프로세스를 관리하거나 제어하는 것이 매우 까다로웠지만, Java 9부터는 새로운 클래스와 인터페이스가 추가되면서 이러한 작업이 훨씬 간편해졌습니다.

대표적으로 ProcessHandleProcessHandle.Info라는 새로운 인터페이스가 도입되었으며, 기존 Process 클래스에도 다양한 새로운 메서드들이 추가되었습니다.

프로세스 트리 탐색 개요

아래 예제에서는 Process API를 활용해 현재 실행 중인 프로세스의 프로세스 트리, 즉 자식(children) 프로세스와 후손(descendants) 프로세스를 탐색하는 방법을 살펴봅니다.

  • children(): 현재 프로세스의 직계 자식 프로세스만 반환합니다.
  • descendants(): 자식 프로세스를 포함해 그 하위의 모든 후손 프로세스를 재귀적으로 반환합니다.

예제 코드

import java.io.IOException;

public class ProcessTreeTest {
    public static void main(String args[]) throws IOException {
        // 외부 프로세스(cmd) 실행
        Runtime.getRuntime().exec("cmd");

        System.out.println("자식 프로세스 목록:");
        ProcessHandle processHandle = ProcessHandle.current();
        processHandle.children().forEach(childProcess ->
                System.out.println("PID: " + childProcess.pid()
                        + " 명령어: " + childProcess.info().command().get()));

        System.out.println("후손 프로세스 목록:");
        processHandle.descendants().forEach(descendantProcess ->
                System.out.println("PID: " + descendantProcess.pid()
                        + " 명령어: " + descendantProcess.info().command().get()));
    }
}

실행 결과

자식 프로세스 목록:
PID: 5092 Command: C:\WINDOWS\System32\cmd.exe
후손 프로세스 목록:
PID: 5092 Command: C:\WINDOWS\System32\cmd.exe
PID: 2256 Command: C:\WINDOWS\System32\conhost.exe

결과 해설

위 실행 결과를 보면 children() 호출 시 직계 자식인 cmd.exe(PID: 5092) 하나만 출력된 반면, descendants() 호출 시에는 cmd.exe와 그 자식인 conhost.exe(PID: 2256)까지 모두 출력됩니다. 즉, descendants()는 프로세스 트리 전체를 재귀적으로 순회한다는 점이 핵심 차이입니다.

또한 childProcess.info().command()는 해당 프로세스를 실행한 실행 파일의 전체 경로를 반환하며, Optional 타입이므로 실제 코드에서는 값이 존재하는지 확인한 후 사용하는 것이 안전합니다.