使用关机钩子时,Java应用程序以错误代码终止

时间:2019-01-30 23:58:46

标签: java shutdown-hook

我有一个ServerSocket应用程序,当用户在终端上键入 Ctrl + C 时终止。应用程序终止清理看起来很好,但是当我尝试查看该进程的返回代码时,它给我SIGTERM的错误代码143和SIGINT的错误代码130。 我希望该过程返回0,因为作业已成功完成


我的代码:

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

向应用发送信号:

kill -s SIGINT <pid>

0 个答案:

没有答案
相关问题