Process process = Runtime.getRuntime().exec(command.toString()); 阻塞卡死

原因:没有读取命令的输出流和错误流,导致缓冲区溢出而阻塞。

工具类封装

package com.oics.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ProcessUtils {
    public static CommandResult exec(String command) throws IOException, InterruptedException {
        Process process = Runtime.getRuntime().exec(command);

        StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream());
        StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream());

        outputGobbler.start();
        errorGobbler.start();

        int isSuccess = process.waitFor();

        outputGobbler.join();
        errorGobbler.join();

        String output = outputGobbler.getOutput();
        String error = errorGobbler.getOutput();

        return new CommandResult(isSuccess, output, error);
    }

    private static class StreamGobbler extends Thread {
        private InputStream inputStream;
        private StringBuilder outputBuilder;

        StreamGobbler(InputStream inputStream) {
            this.inputStream = inputStream;
            this.outputBuilder = new StringBuilder();
        }

        public void run() {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    outputBuilder.append(line).append("\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public String getOutput() {
            return outputBuilder.toString();
        }
    }

    public static class CommandResult {
        private int isSuccess;
        private String output;
        private String error;

        CommandResult(int isSuccess, String output, String error) {
            this.isSuccess = isSuccess;
            this.output = output;
            this.error = error;
        }

        public int getIsSuccess() {
            return isSuccess;
        }

        public String getOutput() {
            return output;
        }

        public String getError() {
            return error;
        }
    }
}
// 待执行的命令
String cmd= "docker ps";
ProcessUtils.CommandResult exec = ProcessUtils.exec(cmd);

// 是否成功
int isSuccess = exec.getIsSuccess();

// 错误信息
String error = exec.getError();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值