H5W3
当前位置:H5W3 > 其他技术问题 > 正文

java 如何关闭服务进程(win+linux) ?

项目运行时会打开很多tcp 端口监听, 每次重启服务总会有个别端口进程还是在运行状态,请问程序如何主动检查端口状态并关闭呢?

回答:

cn.hutool.core.net.NetUtil#isUsableLocalPort(port)

isUsableLocalPort(int port)
检测本地端口可用性
来自org.springframework.util.SocketUtils

上面方法如果不想引入jar:

    public static boolean isUsableLocalPort(int port) {
        // issue#765@Github, 某些绑定非127.0.0.1的端口无法被检测到
        try (ServerSocket ss = new ServerSocket(port)) {
            ss.setReuseAddress(true);
        } catch (IOException ignored) {
            return false;
        }

        try (DatagramSocket ds = new DatagramSocket(port)) {
            ds.setReuseAddress(true);
        } catch (IOException ignored) {
            return false;
        }

        return true;
    }

windows 查找端口占用进程,无windows系统未验证

    public static void main(String[] args) throws IOException, InterruptedException {
        ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/C", "netstat -n -o | findstr :12345");
        Process process = builder.start();
        process.waitFor();
        printProcessStreamAndKill(process.getInputStream());
    }

    private static void printProcessStream(InputStream inputStream) throws IOException {
        int bytesRead = -1;
        byte[] bytes = new byte[1024];
        String output = "";
        while ((bytesRead = inputStream.read(bytes)) > -1) {
            output = output + new String(bytes, 0, bytesRead);
        }
        System.out.println(" The netstat command response is \r\n" + output);
    }

    public static void killProcess(String pid) throws Exception {
        Runtime.getRuntime().exec(KILL + pid);
    }

linux 同样的方式,命令为

  1. 查找端口占用进程:lsof -i:12345
  2. 关闭进程:kill -9 ${pid}

本文地址:H5W3 » java 如何关闭服务进程(win+linux) ?

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址