首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >java Runtime.exec()执行shell/cmd命令:常见的几种陷阱与一种完善实现

java Runtime.exec()执行shell/cmd命令:常见的几种陷阱与一种完善实现

原创
作者头像
刘大猫
发布于 2024-11-17 10:41:05
发布于 2024-11-17 10:41:05
1K0
举报
文章被收录于专栏:JAVA相关JAVA相关

@toc

背景说明

我们项目要java执行命令“dmidecode -s system-uuid”获取结果,然而碰到问题,当项目一直执行好久后,Runtime.getRuntime().exec()获取结果为空,但也不报错,重启项目就又可以了,所以猜测属于陷阱2,并进行记录。

Runtime.getRuntime().exec()执行JVM之外的程序:常见的几种陷阱

前言

日常java开发中,有时需要通过java运行其它应用功程序,比如shell命令等。jdk的Runtime类提供了这样的方法。首先来看Runtime类的文档, 从文档中可以看出,每个java程序只会有一个Runtime实例,显然这是一个单例模式。

代码语言:java
AI代码解释
复制
/**
 * Every Java application has a single instance of class
 * <code>Runtime</code> that allows the application to interface with
 * the environment in which the application is running. The current
 * runtime can be obtained from the <code>getRuntime</code> method.
 * <p>
 * An application cannot create its own instance of this class.
 */
 public class Runtime {
    private static Runtime currentRuntime = new Runtime();

    /**
     * Returns the runtime object associated with the current Java application.
     * Most of the methods of class <code>Runtime</code> are instance
     * methods and must be invoked with respect to the current runtime object.
     *
     * @return  the <code>Runtime</code> object associated with the current
     *          Java application.
     */
    public static Runtime getRuntime() {
        return currentRuntime;
    }

    /** Don't let anyone else instantiate this class */
    private Runtime() {}

    ......
}

要运行JVM中外的程序,Runtime类提供了如下方法,详细使用方法可参见源码注释

代码语言:java
AI代码解释
复制
public Process exec(String command) throws IOException

public Process exec(String cmdarray[]) throws IOException

public Process exec(String command, String[] envp) throws IOException

public Process exec(String command, String[] envp, File dir) throws IOException

public Process exec(String[] cmdarray, String[] envp) throws IOException

public Process exec(String[] cmdarray, String[] envp, File dir) throws IOException

通过这种方式运行外部程序,有几个陷阱需要注意,本文尝试总结常见的几个陷阱,并给出相应的解决方法。同时封装一种比较完善的工具类,用来运行外部应用,并提供超时功能。

Runtime.exec()常见的几种陷阱以及避免方法

陷阱1:IllegalThreadStateException

通过exec执行java命令为例子,最简单的方式如下。执行exec后,通过Process获取外部进程的返回值并输出。

代码语言:java
AI代码解释
复制
import java.io.IOException;

/**
 * Created by yangjinfeng02 on 2016/4/27.
 */
public class Main {

    public static void main(String[] args) {
        Runtime runtime = Runtime.getRuntime();
        try {
            Process process = runtime.exec("java");
            int exitVal = process.exitValue();
            System.out.println("process exit value is " + exitVal);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

很遗憾的是,我们发现输出结果如下,抛出了IllegalThreadStateException异常

代码语言:java
AI代码解释
复制
Exception in thread "main" java.lang.IllegalThreadStateException: process has not exited
at java.lang.ProcessImpl.exitValue(ProcessImpl.java:443)
at com.baidu.ubqa.agent.runner.Main.main(Main.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

为什么会抛出IllegalThreadStateException异常?

这是因为外部线程还没有结束,这个时候去获取退出码,exitValue()方法抛出了异常。看到这里读者可能会问,为什么这个方法不能阻塞到外部进程结束后再返回呢?确实如此,Process有一个waitFor()方法,就是这么做的,返回的也是退出码。因此,我们可以用waitFor()方法替换exitValue()方法。

陷阱2:Runtime.exec()可能hang住,甚至死锁

首先看下Process类的文档说明

代码语言:java
AI代码解释
复制
 * <p>By default, the created subprocess does not have its own terminal
 * or console.  All its standard I/O (i.e. stdin, stdout, stderr)
 * operations will be redirected to the parent process, where they can
 * be accessed via the streams obtained using the methods
 * {@link #getOutputStream()},
 * {@link #getInputStream()}, and
 * {@link #getErrorStream()}.
 * The parent process uses these streams to feed input to and get output
 * from the subprocess.  Because some native platforms only provide
 * limited buffer size for standard input and output streams, failure
 * to promptly write the input stream or read the output stream of
 * the subprocess may cause the subprocess to block, or even deadlock.

从这里可以看出,Runtime.exec()创建的子进程公用父进程的流,不同平台上,父进程的stream buffer可能被打满导致子进程阻塞,从而永远无法返回。

针对这种情况,我们只需要将子进程的stream重定向出来即可。

代码语言:java
AI代码解释
复制
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by yangjinfeng02 on 2016/4/27.
 */
public class Main {

    public static void main(String[] args) {
        List<String> strList = new ArrayList<>();
    Process process = null;
    InputStreamReader ir = null;
    LineNumberReader input = null;
    InputStreamReader errorStream = null;
    LineNumberReader errorReader = null;
    
    try {
        process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", shStr});
        
        // 处理标准输出流
        ir = new InputStreamReader(process.getInputStream());
        input = new LineNumberReader(ir);
        String line;
        while ((line = input.readLine()) != null){
            line = line.replaceAll(" ","");
            strList.add(line.toUpperCase());
        }
        
        // 处理错误输出流
        errorStream = new InputStreamReader(process.getErrorStream());
        errorReader = new LineNumberReader(errorStream);
        String errorLine;
        while ((errorLine = errorReader.readLine()) != null) {
            // 可以选择处理错误信息,或者直接打印出来
            System.err.println("Error output: " + errorLine);
        }
        
        // 等待命令执行结束
        process.waitFor();
        
    } catch (Exception e) {
        log.error("执行Shell命令失败", e);
    } finally {
        try {
            // 关闭输入流和错误流
            if (input != null) {
                input.close();
            }
            if (ir != null) {
                ir.close();
            }
            if (errorReader != null) {
                errorReader.close();
            }
            if (errorStream != null) {
                errorStream.close();
            }
            // 销毁进程
            if (process != null) {
                process.destroy();
            }
        } catch (IOException e) {
            log.error("关闭Shell流失败", e);
        }
    }
    return strList;
    }
}

陷阱3:不同平台上,命令的兼容性

如果要在windows平台上运行dir命令,如果直接指定命令参数为dir,会提示命令找不到。而且不同版本windows系统上,运行改命令的方式也不一样。对这宗情况,需要根据系统版本进行适当区分。

代码语言:java
AI代码解释
复制
String osName = System.getProperty("os.name" );
String[] cmd = new String[3];
if(osName.equals("Windows NT")) {
    cmd[0] = "cmd.exe" ;
    cmd[1] = "/C" ;
    cmd[2] = args[0];
} else if(osName.equals("Windows 95")) {
    cmd[0] = "command.com" ;
    cmd[1] = "/C" ;
    cmd[2] = args[0];
}  
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);

陷阱4:错把Runtime.exec()的command参数当做命令行

本质上来讲,Runtime.exec()的command参数只是一个可运行的命令或者脚本,并不等效于Shell解器或者Cmd.exe,如果你想进行输入输出重定向,pipeline等操作,则必须通过程序来实现。不能直接在command参数中做。例如,下面的例子

代码语言:java
AI代码解释
复制
Process process = runtime.exec("java -version > a.txt");

这样并不会产出a.txt文件。要达到这种目的,需通过编程手段实现,如下

代码语言:java
AI代码解释
复制
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;

/**
 * Created by yangjinfeng02 on 2016/4/27.
 */
class StreamGobbler extends Thread {
    InputStream is;
    String type;
    OutputStream os;

    StreamGobbler(InputStream is, String type) {
        this(is, type, null);
    }

    StreamGobbler(InputStream is, String type, OutputStream redirect) {
        this.is = is;
        this.type = type;
        this.os = redirect;
    }

    public void run() {
        try {
            PrintWriter pw = null;
            if (os != null)
                pw = new PrintWriter(os);

            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
                if (pw != null)
                    pw.println(line);
                System.out.println(type + ">" + line);
            }
            if (pw != null)
                pw.flush();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

public class Main {
    public static void main(String args[]) {
        try {
            FileOutputStream fos = new FileOutputStream("logs/a.log");
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec("cmd.exe /C dir");

            // 重定向输出流和错误流
            StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
            StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT", fos);

            errorGobbler.start();
            outputGobbler.start();
            int exitVal = proc.waitFor();
            System.out.println("ExitValue: " + exitVal);
            fos.flush();
            fos.close();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}

一个比较完善的工具类

下面提供一种比较完善的实现,提供了超时功能。

封装返回结果

代码语言:java
AI代码解释
复制
/**
* ExecuteResult.java
*/
import lombok.Data;
import lombok.ToString;

@Data
@ToString
public class ExecuteResult {
    private int exitCode;
    private String executeOut;

    public ExecuteResult(int exitCode, String executeOut) {
        this.exitCode = exitCode;
        this.executeOut = executeOut;
    }
}

对外接口

代码语言:java
AI代码解释
复制
/**
* LocalCommandExecutor.java
*/
public interface LocalCommandExecutor {
    ExecuteResult executeCommand(String command, long timeout);
}

StreamGobbler类,用来完成stream的管理

代码语言:java
AI代码解释
复制
/**
* StreamGobbler.java
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

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

public class StreamGobbler extends Thread {
    private static Logger logger = LoggerFactory.getLogger(StreamGobbler.class);
    private InputStream inputStream;
    private String streamType;
    private StringBuilder buf;
    private volatile boolean isStopped = false;

    /**
     * @param inputStream the InputStream to be consumed
     * @param streamType  the stream type (should be OUTPUT or ERROR)
     */
    public StreamGobbler(final InputStream inputStream, final String streamType) {
        this.inputStream = inputStream;
        this.streamType = streamType;
        this.buf = new StringBuilder();
        this.isStopped = false;
    }

    /**
     * Consumes the output from the input stream and displays the lines consumed
     * if configured to do so.
     */
    @Override
    public void run() {
        try {
            // 默认编码为UTF-8,这里设置编码为GBK,因为WIN7的编码为GBK
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "GBK");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                this.buf.append(line + "\n");
            }
        } catch (IOException ex) {
            logger.trace("Failed to successfully consume and display the input stream of type " + streamType + ".", ex);
        } finally {
            this.isStopped = true;
            synchronized (this) {
                notify();
            }
        }
    }

    public String getContent() {
        if (!this.isStopped) {
            synchronized (this) {
                try {
                    wait();
                } catch (InterruptedException ignore) {
                    ignore.printStackTrace();
                }
            }
        }
        return this.buf.toString();
    }
}

实现类

通过SynchronousQueue队列保证只有一个线程在获取外部进程的退出码,由线程池提供超时功能。

代码语言:java
AI代码解释
复制
/**
* LocalCommandExecutorImpl.java
*/
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class LocalCommandExecutorImpl implements LocalCommandExecutor {

    static final Logger logger = LoggerFactory.getLogger(LocalCommandExecutorImpl.class);

    static ExecutorService pool = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 3L, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>());

    public ExecuteResult executeCommand(String command, long timeout) {
        Process process = null;
        InputStream pIn = null;
        InputStream pErr = null;
        StreamGobbler outputGobbler = null;
        StreamGobbler errorGobbler = null;
        Future<Integer> executeFuture = null;
        try {
            logger.info(command.toString());
            process = Runtime.getRuntime().exec(command);
            final Process p = process;

            // close process's output stream.
            p.getOutputStream().close();

            pIn = process.getInputStream();
            outputGobbler = new StreamGobbler(pIn, "OUTPUT");
            outputGobbler.start();

            pErr = process.getErrorStream();
            errorGobbler = new StreamGobbler(pErr, "ERROR");
            errorGobbler.start();

            // create a Callable for the command's Process which can be called by an Executor
            Callable<Integer> call = new Callable<Integer>() {
                public Integer call() throws Exception {
                    p.waitFor();
                    return p.exitValue();
                }
            };

            // submit the command's call and get the result from a
            executeFuture = pool.submit(call);
            int exitCode = executeFuture.get(timeout, TimeUnit.MILLISECONDS);
            return new ExecuteResult(exitCode, outputGobbler.getContent());

        } catch (IOException ex) {
            String errorMessage = "The command [" + command + "] execute failed.";
            logger.error(errorMessage, ex);
            return new ExecuteResult(-1, null);
        } catch (TimeoutException ex) {
            String errorMessage = "The command [" + command + "] timed out.";
            logger.error(errorMessage, ex);
            return new ExecuteResult(-1, null);
        } catch (ExecutionException ex) {
            String errorMessage = "The command [" + command + "] did not complete due to an execution error.";
            logger.error(errorMessage, ex);
            return new ExecuteResult(-1, null);
        } catch (InterruptedException ex) {
            String errorMessage = "The command [" + command + "] did not complete due to an interrupted error.";
            logger.error(errorMessage, ex);
            return new ExecuteResult(-1, null);
        } finally {
            if (executeFuture != null) {
                try {
                    executeFuture.cancel(true);
                } catch (Exception ignore) {
                    ignore.printStackTrace();
                }
            }
            if (pIn != null) {
                this.closeQuietly(pIn);
                if (outputGobbler != null && !outputGobbler.isInterrupted()) {
                    outputGobbler.interrupt();
                }
            }
            if (pErr != null) {
                this.closeQuietly(pErr);
                if (errorGobbler != null && !errorGobbler.isInterrupted()) {
                    errorGobbler.interrupt();
                }
            }
            if (process != null) {
                process.destroy();
            }
        }
    }

    private void closeQuietly(Closeable c) {
        try {
            if (c != null) {
                c.close();
            }
        } catch (IOException e) {
            logger.error("exception", e);
        }
    }
}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
【转】Java中Runtime.exec的一些事 
Runtime类是一个与JVM运行时环境有关的Singleton类,有以下几个值得注意的地方:
yiduwangkai
2019/09/17
3.2K0
Linux:java通过Runtime.getRuntime().exec()执行shell,Process.waitFor()返回Required key not available(126)问题
因为看到错误码对应的原因是:Required key not available,所需的Key不可用。查找了很多相关解决办法,发现都不太相关。
鲲志说
2025/04/07
1330
Linux:java通过Runtime.getRuntime().exec()执行shell,Process.waitFor()返回Required key not available(126)问题
Java调用CMD命令
Windows下复制: copy C:\server\data\ccgavr\1.png C:\server\data\ccgavr\2.png Windows重命名: ren 1.png 3.png ren C:\server\data\ccgavr\1.png C:\server\data\ccgavr\3.png(DOS中提示命令语法不正确,powershell则可以)
JaneYork
2023/10/11
4840
Java调用CMD命令
Process类详解
ProcessBuilder是一个final类,Process是一个抽象类。ProcessBuilder.start() 和 Runtime.exec() 方法都被用来创建一个操作系统进程(执行命令行操作),并返回 Process 子类的一个实例,该实例可用来控制进程状态并获得相关信息。
matt
2022/10/25
1.8K0
利用UiAutomator写一个首页刷新的稳定性测试脚本
本人在做Android APP稳定性测试的过程中,需要测试在不断刷新首页内容的场景下的稳定运行和性能数据的收集。最终根据UiAutomator+多线程解决了这个问题。思路如下:先用UiAutomator编写好运行脚本,然后在使用快速调试的时候把调试命令输出出来,然后在测试脚本中运行这个调试命令即可,当然还需要多线程来辅助记录log和性能数据。
FunTester
2019/09/04
7240
在 Java 中进行类似于 Python 的系统调用
Python 中有一个内置函数 popen2,可以用来执行系统命令并获取其输出和状态信息。在 Java 中,是否有与之类似的函数或类,可以实现同样的功能?
用户11021319
2024/07/12
2380
在 Java 中进行类似于 Python 的系统调用
java 执行shell命令及日志收集避坑指南
有时候我们需要调用系统命令执行一些东西,可能是为了方便,也可能是没有办法必须要调用。涉及执行系统命令的东西,则就不能做跨平台了,这和java语言的初衷是相背的。
烂猪皮
2021/01/14
2.8K0
Java执行Shell命令的方式
Java可以使用Runtime和ProcessBuilder两种方式执行Shell命令。
很酷的站长
2023/09/24
3.9K0
Java执行Shell命令的方式
Runtime.getRuntime().exec执行scp失败
1.本地scp命令正常 [root@hadron ~]# scp /root/scripts/* 192.168.1.157:/opt Step1.sh 100% 340 0.3KB/s 00:00 Step2.sh
程裕强
2022/05/06
6150
java实现定时备份/手动备份还原mysql数据库
定时备份与还原 简介:配置一个时间监听器,通过util中的日期类和定时器控件解析相关的时间数据,在相应的时间调用备份数据库的方法. 备份数据库的方法使用了mysql自带的mysqldump进行备份,得到数据库的sql文件,完成备份. 下面是具体的实现 首先,相关配置文件,放在文件类路径下 (dbBackUpRecover.properties) #smysql备份功能路径与数据库用户名和密码 #//usr//bin 为mysql服务bin目录的地址 -u后为用户名 -p后为密码 最后一
洋仔聊编程
2019/01/15
6.8K2
深入研究java.lang.Runtime类(转)
一、概述 Runtime类封装了运行时的环境。每个 Java 应用程序都有一个 Runtime 类实例,使应用程序能够与其运行的环境相连接。 一般不能实例化一个Runtime对象,应用程序也不能创建自己的 Runtime 类实例,但可以通过 getRuntime 方法获取当前Runtime运行时对象的引用。 一旦得到了一个当前的Runtime对象的引用,就可以调用Runtime对象的方法去控制Java虚拟机的状态和行为。 当Applet和其他不被信任的代码调用任何Runtime方法时,常常会引起SecurityException异常。
HUC思梦
2020/09/03
7400
Kotlin 扩展函数与属性 实例代码
Java package com.easykotlin.lec03_kotlin_extensions; import java.util.List; public class CollectionUtils { public static void swap(List<Integer> list, int src, int target) { int temp = list.get(src); list.set(src, list.get(target));
一个会写诗的程序员
2018/11/21
6080
Java调用SqlLoader将大文本导入数据库
  分析:通过Java的IO流解析txt文本文档,拼接动态sql实现insert入库,可以实现,缺点如下
sunny1009
2022/05/06
1.3K0
Java调用SqlLoader将大文本导入数据库
用Java代码备份和还原MySQL数据库
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Outpu
用户8671053
2021/09/22
3.9K0
mySql每天自动备份数据库
工具类 package cn.stylefeng.guns.modular.task; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.*; import java.nio.charset.StandardCharsets; /** * @author shiye * @create 2022-06-22 16:27 */ public cla
用户5927264
2022/06/26
2.7K0
JAVA调用FFMpeg进行转码等操作
直接上代码: public abstract class FFmpegUtils { FFmpegUtils ffmpegUtils; int timeLengthSec
JQ实验室
2022/02/14
1.8K0
Java 配 Shell 等于美酒加咖啡
技术上又何尝不是如此呢?先假设一个场景:BOSS 让你实现一个服务监控的指挥室,能看到每个服务器的磁盘剩余空间,能看到。。。能看到。。。
一猿小讲
2019/09/17
9040
Java 配 Shell 等于美酒加咖啡
linux下的shell命令的编写,以及java如何调用linux的shell命令(java如何获取linux上的网卡的ip信息)
最近在开发中,需要用到服务器的ip和mac信息。但是服务器是架设在linux系统上的,对于多网口,在获取ip时就产生了很大的问题。下面是在windows系统上,java获取本地ip的方法。贴代码:
业余草
2019/01/21
2.6K0
linux下的shell命令的编写,以及java如何调用linux的shell命令(java如何获取linux上的网卡的ip信息)
Java魔法堂:找外援的利器——Runtime.exec详解
一、前言                                  Java虽然五脏俱全但总有软肋,譬如获取CPU等硬件信息,当然我们可以通过JNI调用C/C++来获取,但对于对C/C++和Windows API不熟的码农是一系列复杂的学习和踩坑过程。那能不能通过简单一些、学习成本低一些的方式呢?答案是肯定的,在功能实现放在首位的情况下,借他山之石是最简洁有力的做法。而 Runtime.exec方法 就为我们打开这么的一条路了。 二、认识 java.lang.Runtime.exec方法   作用
^_^肥仔John
2018/01/18
1.8K0
Java魔法堂:找外援的利器——Runtime.exec详解
Java判断计算机网络连接是否正常
用户在登录系统时,出现网络断开,从而系统自动检测到网络状态。 /** * @author 麦克劳林 * @功能:持续检测网络是否连通 */ import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.Date; publi
麦克劳林
2018/09/11
2.3K0
相关推荐
【转】Java中Runtime.exec的一些事 
更多 >
交个朋友
加入腾讯云官网粉丝站
蹲全网底价单品 享第一手活动信息
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档