package com.ym.mec.util.shell;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

public class ScriptUtil {
    private final static Logger log = LoggerFactory.getLogger(ScriptUtil.class);
    /**
     * 调用shell脚本
     *
     * @param cmd
     */
    public static int callScript(String cmd) {
        Runtime run = Runtime.getRuntime();
        //执行结果
        int result = 1;
        try {
            Process p = run.exec(cmd);
            InputStream ins = p.getInputStream();
            InputStream ers = p.getErrorStream();
            //启动两个线程，一个线程负责读标准输出流，另一个负责读标准错误流
            new Thread() {
                public void run() {
                    BufferedReader br1 = new BufferedReader(new InputStreamReader(ins));
                    try {
                        String line1 = null;
                        while ((line1 = br1.readLine()) != null) {
                            if (line1 != null) {
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            ins.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();

            new Thread() {
                public void run() {
                    BufferedReader br2 = new BufferedReader(new InputStreamReader(ers));
                    try {
                        String line2 = null;
                        while ((line2 = br2.readLine()) != null) {
                            if (line2 != null) {
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            ers.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();

            //等待shell脚本结果
            int execStatus = p.waitFor();
            log.info("执行runtime的脚本end");


            log.info("shell脚本执行结果--execStatus =" + execStatus);


            result = execStatus;
            log.info("返回值为result=" + result);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return result;
    }
}
