ubuntu java启动shell脚本

时间:2021-06-28 17:45:28   收藏:0   阅读:0
    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();
    }
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!