프로세스(Process)

운영체제로부터 자원을 할당받는 작업의 단위

사용자가 어플리케이션을 실행하면, 운영체제로부터 실행에 필요한 메모리를 할당받아 어플리케이션의 코드를 실행하는데 이것을 프로세스라고 부른다.

 

ex) Chrome 브라우저 2개 실행 = 두 개의 Chrome 프로세스가 생성 되었다.

 

자바에서 프로세스는 자바 가상 머신(JVM)이 운영체제에서 프로그램을 실행할때 생성된다. 프로세스는 독립된 실행 환경을 가지며, 다음과 같은 특징을 가진다.

  1. 독립된 주소 공간 : 프로세스는 자신의 메모리 공간을 독립적으로 가지고 있다. 다른 프로세스와 메모리 공간을 공유하지 않기 때문에 하나의 프로세스에서 발생한 오류가 다른 프로세스에 영향을 미치지 않는다.
  2. 자원 할당 : 프로세스는 CPU 시간, 메모리, 파일 핸들 등의 자원을 할당받는다.
  3. 프로세스 간 통신 : 서로 다른 프로세스는 기본적으로 독립적이기 때문에, 프로레스 간의 데이터 교환은 인터프로세스 커뮤니케이션(IPC) 기법을 통해 이루어져야 한다. IPC 방법으로는 소켓, 파일, 공유 메모리, 메시지 큐 등이 있다.

자바에서 새로운 프로세스를 생성하려면 

  1. Runtime.getRuntime().exec() 메서드를 사용하거나
  2. ProcessBuilder 클래스를 사용할 수 있습니다.

 

Runtime 클래스의 exec 메서드를  사용

import java.io.*;

public class ProcessExample {
    public static void main(String[] args) {
        try {
            // 새로운 프로세스를 생성하여 명령어 실행
            Process process = Runtime.getRuntime().exec("notepad.exe");

            // 프로세스의 출력 스트림 읽기 (예시에서는 필요 없지만 다른 명령어 실행 시 유용할 수 있음)
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 프로세스 종료 대기
            int exitCode = process.waitFor();
            System.out.println("Process exited with code: " + exitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

 

 

ProcessBuilder 클래스를 사용하는 예시

mport java.io.*;

public class ProcessBuilderExample {
    public static void main(String[] args) {
        // ProcessBuilder 객체 생성
        ProcessBuilder processBuilder = new ProcessBuilder("ping", "-c", "4", "google.com");

        // 프로세스 출력과 오류를 동일한 스트림으로 병합
        processBuilder.redirectErrorStream(true);

        try {
            // 새로운 프로세스 시작
            Process process = processBuilder.start();

            // 프로세스의 출력 스트림 읽기
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 프로세스 종료 대기
            int exitCode = process.waitFor();
            System.out.println("Process exited with code: " + exitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

 

 

프로세스 간 통신 예시

자바에서는 소켓을 사용하여 프로세스 간 통신을 구현할 수 있다. 간단한 서버-클라이언트 예제를 통해 프로세스 간 통신을 알아보자

 

서버 예제

import java.io.*;
import java.net.*;

public class Server {
    public static void main(String[] args) {
        // 서버 소켓을 생성하여 포트 5000에서 클라이언트 연결 대기
        try (ServerSocket serverSocket = new ServerSocket(5000)) {
            System.out.println("Server started. Waiting for a client...");

            // 클라이언트 연결 수락
            try (Socket clientSocket = serverSocket.accept();
                 // 클라이언트와 통신을 위한 출력 스트림 생성
                 PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
                 // 클라이언트와 통신을 위한 입력 스트림 생성
                 BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) {

                System.out.println("Client connected.");

                String inputLine;
                // 클라이언트로부터 데이터 수신 및 처리
                while ((inputLine = in.readLine()) != null) {
                    System.out.println("Received: " + inputLine);
                    // 클라이언트로 데이터 전송
                    out.println("Echo: " + inputLine);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

클라이언트 예제

import java.io.*;
import java.net.*;

public class Client {
    public static void main(String[] args) {
        // 서버에 연결
        try (Socket socket = new Socket("localhost", 5000);
             // 서버로 데이터 전송을 위한 출력 스트림 생성
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
             // 서버로부터 데이터 수신을 위한 입력 스트림 생성
             BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             // 사용자 입력을 위한 표준 입력 스트림 생성
             BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) {

            String userInput;
            // 사용자 입력을 읽어 서버로 전송하고, 서버의 응답을 출력
            while ((userInput = stdIn.readLine()) != null) {
                out.println(userInput);
                System.out.println("Server response: " + in.readLine());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

이 예시는 서버가 클라이언트의 메시지를 받아 그대로 돌려주는 간단한 코드이다. 

'Back-End > Java' 카테고리의 다른 글

try-catch  (0) 2024.07.06
스레드  (1) 2024.07.05
Java HTTP 통신  (4) 2024.06.12
Exception과 Transaction  (1) 2024.02.05
String, StringBuilder, StringBuffer 의 차이점  (1) 2023.10.26

+ Recent posts