0

I have a ServerSocket application that terminates when the user type Ctrl + C on the terminal. The application termination cleanup looks fine, but when I tried to see the returned code of the process it gives me an error code 143 for SIGTERM and 130 for SIGINT. I would like the process to return 0 because the job was successfully done.


My code:

public class Application {
    public static void main(String[] args) {
        WebService webService = new WebService(9999);
        Thread serviceThread = new Thread(webService);
        serviceThread.start();

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            webService.stop();

            try {
                serviceThread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }));
    }
}

public class WebService implements Runnable {
    private int port;
    private ServerSocket socket;

    public WebService(int port) {
        this.port = port;
    }

    @Override
    public void run() {
        try {
            socket = new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();
        }

        while (!socket.isClosed()) {
            try {
                socket.accept();
                System.out.println("New client connected!");
            } catch (IOException e) {
                if (!socket.isClosed())
                    e.printStackTrace();
                break;
            }
        }

        cleanup();
    }

    private void cleanup() {
        System.out.println("Stopping server");
        for (int i = 0; i < 3; i++) {
            try {
                System.out.print(".");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("\nServer stopped!");
    }

    public void stop() {
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Running the application:
$ java -jar App.jar || echo $?
Stopping server
...
Server stopped!
130

Sending signal to the application:

kill -s SIGINT <pid>
Michael Pacheco
  • 948
  • 1
  • 17
  • 25

0 Answers0