When Runtime.exec() won't - Runtime.exec的陷阱

本文总结了使用Java进行进程管理时常见的陷阱及解决方案,包括如何正确获取外部进程的退出状态、及时处理进程的输入输出流,以及如何避免使用Runtime.exec()执行复杂命令行操作。

     原文比较长,在这里就不转载了,给出地址:http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=1

  1. 文中总结了几个要点:
    You cannot obtain an exit status from an external process until it has exited
    直到一个外部进程退出,你才能获取其退出状态值。
    正确代码
    int exitVal = proc.waitFor();
     缺陷代码
    int exitVal = proc.exitValue();
     
  2. You must immediately handle the input, output, and error streams from your spawned external process
    你必须马上处理从外部进程获得的大量输入、输出以及错误流(如果存在的话)。之所以要这样来做,是因为“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, and even deadlock.”。(来自Java Doc:某些本地平台只提供了有限的buffer给标准输入、输出流。一旦写入失败,子进程就有可能被阻塞甚至死锁。)
    正确代码
    import java.util.*;
    import java.io.*;
    public class MediocreExecJavac
    {
        public static void main(String args[])
        {
            try
            {            
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec("javac");
                InputStream stderr = proc.getErrorStream();
                InputStreamReader isr = new InputStreamReader(stderr);
                BufferedReader br = new BufferedReader(isr);
                String line = null;
                System.out.println("<ERROR>");
                while ( (line = br.readLine()) != null)
                    System.out.println(line);
                System.out.println("</ERROR>");
                int exitVal = proc.waitFor();
                System.out.println("Process exitValue: " + exitVal);
            } catch (Throwable t)
              {
                t.printStackTrace();
              }
        }
    }
      
    缺陷代码
    import java.util.*;
    import java.io.*;
    public class BadExecJavac2
    {
        public static void main(String args[])
        {
            try
            {            
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec("javac");
                int exitVal = proc.waitFor();
                System.out.println("Process exitValue: " + exitVal);
            } catch (Throwable t)
              {
                t.printStackTrace();
              }
        }
    }
    
      
  3. You must use Runtime.exec() to execute programs
     你必须使用Runtime.exec()来执行程序(这句我不太理解)
  4. You cannot use Runtime.exec() like a command line
    你不能用Runtime.exec()来执行像命令行那样的程序,如重定向输出:Process proc = rt.exec("java jecho 'Hello World' > test.txt"); 
    这段程序的意图是运行一个名为jecho的Java程序,并将其输出重定向到test.txt文件中。 但这种写法得不到正确结果,因为Runtime.exec()方法并不能很好的执行这种较为复杂的命令行,必须通过自己处理程序输出并写入到相应的文件

 最后给出完整的代码:

Class StreamGobbler 用于处理输出流:

import java.util.*;
import java.io.*;
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=null;
            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();  
            }
    }
}

 TestExec则是测试用的main class

import java.util.*;
import java.io.*;
public class TestExec
{
    public static void main(String args[])
    {
        if (args.length < 1)
        {
            System.out.println("USAGE: java TestExec \"cmd\"");
            System.exit(1);
        }
        
        try
        {
            String cmd = args[0];
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(cmd);
            
            // any error message?
            StreamGobbler errorGobbler = new 
                StreamGobbler(proc.getErrorStream(), "ERR");            
            
            // any output?
            StreamGobbler outputGobbler = new 
                StreamGobbler(proc.getInputStream(), "OUT");
                
            // kick them off
            errorGobbler.start();
            outputGobbler.start();
                                    
            // any error???
            int exitVal = proc.waitFor();
            System.out.println("ExitValue: " + exitVal);
        } catch (Throwable t)
          {
            t.printStackTrace();
          }
    }
}

 

测试例子: java TestExec "iexplore www.sina.com.cn" (因为iexplore.exe已经在windows的环境变量Path中,所以这些调用没有问题,否则就要写绝对路径) 

=> ERROR [2/6] RUN yum install -y java-17-openjdk-devel 2.5s ------ > [2/6] RUN yum install -y java-17-openjdk-devel: 1.858 Loaded plugins: fastestmirror, ovl 2.200 Determining fastest mirrors 2.265 Could not retrieve mirrorlist http://mirrorlist.centos.org/?release=7&arch=x86_64&repo=os&infra=container error was 2.265 14: curl#6 - "Could not resolve host: mirrorlist.centos.org; Unknown error" 2.284 2.284 2.284 One of the configured repositories failed (Unknown), 2.284 and yum doesn't have enough cached data to continue. At this point the only 2.284 safe thing yum can do is fail. There are a few ways to work "fix" this: 2.284 2.284 1. Contact the upstream for the repository and get them to fix the problem. 2.284 2.284 2. Reconfigure the baseurl/etc. for the repository, to point to a working 2.284 upstream. This is most often useful if you are using a newer 2.284 distribution release than is supported by the repository (and the 2.284 packages for the previous distribution release still work). 2.284 2.284 3. Run the command with the repository temporarily disabled 2.284 yum --disablerepo=<repoid> ... 2.284 2.284 4. Disable the repository permanently, so yum won't use it by default. Yum 2.284 will then just ignore the repository until you permanently enable it 2.284 again or use --enablerepo for temporary usage: 2.284 2.284 yum-config-manager --disable <repoid> 2.284 or 2.284 subscription-manager repos --disable=<repoid> 2.284 2.284 5. Configure the failing repository to be skipped, if it is unavailable. 2.284 Note that yum will try to contact the repo. when it runs most commands, 2.284 so will have to try and fail each time (and thus. yum will be be much 2.284 slower). If it is a very temporary problem though, this is often a nice 2.284 compromise: 2.284 2.284 yum-config-manager --save --setopt=<repoid>.skip_if_unavailable=true 2.284 2.284 Cannot find a valid baseurl for repo: base/7/x86_64 ------ Dockerfile:5 -------------------- 3 | 4 | # 安装完整 JDK(必须包含 -devel 包) 5 | >>> RUN yum install -y java-17-openjdk-devel 6 | 7 | # 设置环境变量(使用标准路径) -------------------- ERROR: failed to solve: process "/bin/sh -c yum install -y java-17-openjdk-devel" did not complete successfully: exit code: 1
06-19
本课题设计了一种利用Matlab平台开发的植物叶片健康状态识别方案,重点融合了色彩与纹理双重特征以实现对叶片病害的自动化判别。该系统构建了直观的图形操作界面,便于用户提交叶片影像并快速获得分析结论。Matlab作为具备高效数值计算与数据处理能力的工具,在图像分析与模式分类领域应用广泛,本项目正是借助其功能解决农业病害监测的实际问题。 在色彩特征分析方面,叶片影像的颜色分布常与其生理状态密切相关。通常,健康的叶片呈现绿色,而出现黄化、褐变等异常色彩往往指示病害或虫害的发生。Matlab提供了一系列图像处理函数,例如可通过色彩空间转换与直方图统计来量化颜色属性。通过计算各颜色通道的统计参数(如均值、标准差及主成分等),能够提取具有判别力的色彩特征,从而为不同病害类别的区分提供依据。 纹理特征则用于描述叶片表面的微观结构与形态变化,如病斑、皱缩或裂纹等。Matlab中的灰度共生矩阵计算函数可用于提取对比度、均匀性、相关性等纹理指标。此外,局部二值模式与Gabor滤波等方法也能从多尺度刻画纹理细节,进一步增强病害识别的鲁棒性。 系统的人机交互界面基于Matlab的图形用户界面开发环境实现。用户可通过该界面上传待检图像,系统将自动执行图像预处理、特征抽取与分类判断。采用的分类模型包括支持向量机、决策树等机器学习方法,通过对已标注样本的训练,模型能够依据新图像的特征向量预测其所属的病害类别。 此类课题设计有助于深化对Matlab编程、图像处理技术与模式识别原理的理解。通过完整实现从特征提取到分类决策的流程,学生能够将理论知识与实际应用相结合,提升解决复杂工程问题的能力。总体而言,该叶片病害检测系统涵盖了图像分析、特征融合、分类算法及界面开发等多个技术环节,为学习与掌握基于Matlab的智能检测技术提供了综合性实践案例。 资源来源于网络分享,仅用于学习交流使用,请勿用于商业,如有侵权请联系我删除!
Building project ... [Trace]: Executing external command: dotnet build E:\正在编写的网站\UserManagementSystem\UserManagementSystem.Web\UserManagementSystem.Web.csproj --configuration Debug --framework net9.0 [Trace]: Executing external command: dotnet exec --runtimeconfig E:\正在编写的网站\UserManagementSystem\UserManagementSystem.Web\bin\Debug\net9.0\UserManagementSystem.Web.runtimeconfig.json --depsfile E:\正在编写的网站\UserManagementSystem\UserManagementSystem.Web\bin\Debug\net9.0\UserManagementSystem.Web.deps.json C:\Users\sunyu\.nuget\packages\microsoft.visualstudio.web.codegeneration.design\9.0.0\lib\net8.0\dotnet-aspnet-codegenerator-design.dll --no-dispatch --port-number 59248 identity --dbContext UserManagementSystem.Web.Data.ApplicationDbContext --userClass UserManagementSystem.Web.Models.ApplicationUser --files Account.Login;Account.Register;Account.Logout;Account.Manage.Index --dispatcher-version 9.0.0 [Trace]: Command Line: --no-dispatch --port-number 59248 identity --dbContext UserManagementSystem.Web.Data.ApplicationDbContext --userClass UserManagementSystem.Web.Models.ApplicationUser --files Account.Login;Account.Register;Account.Logout;Account.Manage.Index --dispatcher-version 9.0.0 Finding the generator 'identity'... Running the generator 'identity'... '--userClass' cannot be used to specify a user class when using an existing DbContext. at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.<BuildCommandLine>b__6_0() at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args) at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.Execute(String[] args) at Microsoft.VisualStudio.Web.CodeGeneration.CodeGenCommand.Execute(String[] args) RunTime 00:00:06.71
10-04
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值