两个程序:CommandTest
执行Linux
命令,将其打成jar包,放在服务器上面执行;SimpleTest
是被CommandTest
调用的命令执行的程序。
服务器上面文件的存放路径:
程序代码:CommandTest
类
public class CommandTest {
public static List<String> getCommandList() {
String path = "/home/huangqiqi/simpleTest";
List<String> commands = new ArrayList<>();
commands.add("cd " + path);
commands.add("ls");
commands.add("ulimit -c unlimited");
commands.add("java -jar SimpleTest.jar > test.out");
return commands;
}
public static void executeCommands(List<String> commands) throws IOException {
for (String cmd : commands) {
System.out.println("execute cmd : " + cmd);
}
Runtime run = Runtime.getRuntime();
Process proc = null;
BufferedReader in = null;
PrintWriter out = null;
boolean isDump = false;
try {
proc = run.exec("/bin/bash", null, null);
in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
for (String line : commands) {
out.println(line);
}
out.println("exit");
String line = "";
while ((line = in.readLine()) != null) {
System.out.println("readLine: " + line);
if (line.indexOf("core.") >= 0) {
isDump = true;
break;
}
}
proc.waitFor();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (proc != null)
proc.destroy();
if (in != null)
in.close();
if (out != null)
out.close();
}
if (isDump) {
System.exit(0);
}
}
public static void main(String[] args) {
List<String> commands = getCommandList();
try {
executeCommands(commands);
} catch (Exception e) {
e.printStackTrace();
}
}
}
程序代码:SimpleTest
类:
public class SimpleTest {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println("Hello World: " + i);
}
}
}