Process 执行shell 可设置超时

Process类执行shell命令

Process类Api

  1. public abstract OutputStream getOutputStream(); 获取输出流
  2. public abstract InputStream getInputStream(); 获取输入流
  3. public abstract InputStream getErrorStream(); 获取错误输入流
  4. public abstract int waitFor(); 阻塞父进程直到子进程退出
  5. public boolean waitFor(long var1, TimeUnit var3) throws InterruptedException; var3(时间)后退出进程
  6. public abstract int exitValue(); 退出当前进程
  7. public abstract void destroy(); 杀掉子进程
  8. public Process destroyForcibly(); 强行杀掉子进程
  9. public boolean isAlive(); 判断子进程是否处理运行状态

shell执行操作

package com.jipf.springboot.test;

import java.io.*;
import java.util.concurrent.*;

/**
 * 执行shell 超时设置
 * @author jipf
 */
public class ShellExec {

	/**
     *
     * @param shell shell命令
     * @param timeout 执行超时时间设置
     * @author jipf
     */
    public static void exec(String shell,long timeout){
        try {
            /**  切换用户执行shell脚本*/	
            //	Process process = Runtime.getRuntime().exec("su " + user);
            //	DataOutputStream os = new DataOutputStream(process.getOutputStream());
            //	os.writeBytes("sqoop --import ...\n");//执行sqoop命令
            //	os.writeBytes("exit\n");
            //	os.flush();
            Process process = Runtime.getRuntime().exec(shell);
            ExecutorService executorService = Executors.newFixedThreadPool(2);
            Future<String> future1 = executorService.submit(()->{return handlerProcessBlock(process.getInputStream());});
            Future<String> future2 = executorService.submit(()->{return handlerProcessBlock(process.getErrorStream());});
            executorService.shoudown();//任务执行完毕退出
            if (process.waitFor(timeout, TimeUnit.MILLISECONDS)){//程序在限定时间内执行完毕
                /* 退出码为0时 属于正常退出**/
                if (process.exitValue() != 0){//执行shell出错 记录错误信息
                    System.out.println(future2.get());
                }
            }else {
                System.out.println("exec time out!");//执行shell超时
                executorService.shoudownNow();//终止线程池任务执行
                os.close();
                process.destroy();//kill 子进程
            }
        }catch (IOException e){
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 处理阻塞问题 清理缓冲区 防止进程阻塞
     * 子线程向缓冲区中写数据,若java虚拟机没有及时的读取缓冲区中的数据,导致缓冲区满了,则主线程会阻塞,此时就会卡住
     * @param inputStream
     * @return
     * @throws IOException
     */
    private static String handlerProcessBlock(InputStream inputStream){
        BufferedReader reader = null;
        try {
            StringBuffer sb = new StringBuffer();
            String buff;
            reader = new BufferedReader(new InputStreamReader(inputStream));
            while ((buff = reader.readLine()) != null) {
                sb.append(buff.trim()).append("\n");
            }
            return sb.toString();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    public static void main(String[] args) {
        exec("ls /opt",1000);
    }
}
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值