如何以异步方式从Java程序中运行shell脚本 [英] how to run shell script asynchronously from within Java program

查看:402
本文介绍了如何以异步方式从Java程序中运行shell脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个Java程序asynchronously--即在Java程序启动shell脚本执行后内运行一个shell脚本,它携带与其他operations--和确实只有一些进一步的工作当shell脚本返回应对之道..即它并没有明确停止,等待shell脚本的响应。

I want to run a shell script from within a Java program asynchronously-- i.e. after the java program starts execution of that shell script, it carries on with other operations-- and does some further work only when the shell script returns a response to it.. i.e. it does not explicitly stop and wait for the shell script's response.

这是可能/可行吗?如何实现这样的功能?

Is this possible/feasible? How do I implement such functionality?

基本上我将监测使用单台服务器的多个服务器,将管理所有这些servers--此它将运行在每台服务器上的shell脚本...因为有很多的服务器,并在Java的建议数量线程不超过CPU的核心数量......所以我需要一个解决这个问题,那就是不依赖于(因为线程限制)线程......这样我能同时(或几乎同时)火过很多这样的无需等待这些脚本响应一shell脚本(如等待会影响其他的shell脚本命令处理)...另外一个问题..在shell命令需要调用无论是在本地机器或远程计算机上,并从需要响应这两种类型的shell脚本执行(即本地执行和远程执行)...

Basically i will be monitoring multiple servers using a single server that will manage all those servers-- for this it will run shell scripts on each of those servers...since there are many servers, and in java its recommended that number of threads not exceed number of cpu cores... hence I need a solution to this problem, that is not dependent on threading (because of threading limitations)...so that I can simultaneously (or near-simultaneously) fire off many such shell scripts without waiting for one of those scripts responses' (as waiting would affect processing for other shell script commands)... another issue.. the shell commands need to be invoked either on local machine or on remote machines and response is needed from both types of shell script execution(viz local execution and remote execution)...

推荐答案

你尝试什么吗?

你可以尝试这样的:

ProcessBuilder builder = new ProcessBuilder("your command to launch script");
Process process = builder.start();

,它不默认情况下,该过程完成等待,这样你就可以执行下你的code。

And it does NOT wait by default for the process to complete, so you can execute your code next.

如果你想要做一些处理过程完成之后,你可以尝试:

And if you want to do some processing after the process is finished you can try:

int exitVal = process.waitFor();

这篇关于如何以异步方式从Java程序中运行shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆