ubuntu java启动shell脚本

    public void startC138() {
        new Thread(() -> {
            try {
                Thread.sleep(10000);
                String killredis = "/home/bjlthy/gym/code/killredis.sh";
                Process ps = Runtime.getRuntime().exec(killredis);
                String logMsg = "----------> java killredis ps.isAlive=" + ps.isAlive();
                System.out.println(logMsg);
                LogHelper.info(logMsg);

                Thread.sleep(5000);

                startC2();

            } catch (Exception e) {
                e.printStackTrace();
                LogHelper.error("startC138", e);
            }
        }).start();
    }

    public void startC2() {
        ProcessBuilder pb;
        Process process = null;
        BufferedReader br = null;
        StringBuilder resMsg = null;
        OutputStream os = null;
        String cmd1 = "/home/bjlthy/gym/code/redis.sh";
        try {
            pb = new ProcessBuilder(cmd1);
            pb.redirectErrorStream(true);
            process = pb.start();
            os = process.getOutputStream();
            os.write(cmd1.getBytes());
            os.flush();
            os.close();

            resMsg = new StringBuilder();

            br = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String s;
            while ((s = br.readLine()) != null) {
                resMsg.append(s + "\n");
            }
            resMsg.deleteCharAt(resMsg.length() - 1);
            int result = process.waitFor();
            System.out.println("result=" + result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            // if (process != null) {
            //     process.destroy();
            // }
        }
        // return resMsg.toString();
    }
posted @ 2021-06-25 18:10  一只桔子2233  阅读(203)  评论(0编辑  收藏  举报