import java.io.*;
public class GnomeCommand {
public static void main(String args[]) throws IOException {
try {
Runtime r = Runtime.getRuntime();
String[] cmdArray = {"/usr/bin/gnome-terminal", "-e", "ps ax | grep gnome", " ; exec $SHELL"};
r.exec(cmdArray).waitFor();
} catch (InterruptedException ex){
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
The problem is I cannot keep the command prompt open. It closes immediately. I also used "exec $SHELL" command but the result is same. I want to keep the terminal open after executing the command.
Your sub process ends when the command execution ends. In your case after ps and grep have finished executing your script will end.
Try with xterm with -hold option
xterm -e "ps ax | grep gnome" -hold
Related
I have the following code to run three executions :
public static void main(String[] args) throws InterruptedException, IOException
{
String filepath1 = "cmd /c gradlew jmhJar";
String filepath2 = "cmd /c java -jar path/to/the/file/filename.jar -rf csv -rff path/to/save/file1.csv -wi 3 -i 5 -f 2";
String filepath4 = "cmd /c javac path/to/the/file/ParserHash.java";/*Code to compile is parserHash.java*/
String filepath3 = "cmd /c java path/to/the/compiled/class/ParserHash "C:/Users/msek/Desktop/trial/result/file1.csv C:/Users/msek/Desktop/trial/result/file2.csv C:/Users/msek/Desktop/trial/result/file3.csv";
try
{
runProcess(filepath1);
runProcess(filepath2);
System.out.println("Sucessfully written into file1.csv");
runProcess(filepath4);
System.out.println("Compilation Over");
runProcess(filepath3);
System.out.println("Program Sucessfully Executed");
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void runProcess(String processString)
{
try
{
final Process p = Runtime.getRuntime().exec(processString);
new Thread(new Runnable() {
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
try {
while ((line = input.readLine()) != null)
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
p.waitFor();
}
catch (Exception x)
{
x.printStackTrace();
}
}
If I compile the java file going to that particular directory and compile its compiling successfully and on running it, it executes successfully. But if I pass it like "cmd /c path/to/java/file/file.java" its getting compiled but when I execute it, I get an error stating that could not find or load mainclass eventhough class file is present.
I have looked various links on this which suggested buid process, but that didn't work.
I just want to know where I'm going wrong and how to compile, execute a java file by passing multiple arguments using Runtime.exec()..
java path/to/the/compiled/class/ParserHash
If you're having trouble with an exec() you should:
Try the command from a command line yourself. It will fail the same way in this case.
Look up the syntax of the command. In this case you will learn that the argument to the java command is not a path but a class name, fully qualified, i.e. including the package name. With dots.
Please know that stanford is not exe. it is a folder consists many programs
I open the cmd.exe by using following statement:
public static void runStanfordCMD() throws IOException{
List<String> cmds = Arrays.asList("cmd.exe", "/C", "start", "java", "-mx4g", "-cp", "*", "edu.stanford.nlp.pipeline.StanfordCoreNLPServer");
ProcessBuilder builder = new ProcessBuilder(cmds);
builder.directory(new File("D:/Desktop/stanford-corenlp-full-2015-12-09"));
Process proc = builder.start();
}
so how to close the cmd.exe after I finished some process?
by using ProcessBuilder or Runtime?
If using ProcessBuilder how to write the statement according to my case?
how to write the statement to the Runtime according to my case?
public static void closeStanfordCMD() throws IOException{
try {
Runtime.getRuntime().exec("command.exe /C" + "Your command"); // how to write the statement?
} catch (Exception e) {
e.printStackTrace();
}
}
The method
Runtime.getRuntime().exec
returns an object of Process.
Process has a method destroy() which kills the process you're running.
So what you need is to store the Process object returned by the exec method and call destroy() on it when you want to kill the process.
Also you can call waitFor() method to wait for the process to stop (Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated).
To make it clear, try this code (or modify for your needs):
try {
Process p = Runtime.getRuntime().exec("java -mx4g -cp * D:/Desktop/stanford-corenlp-full-2015-12-09/edu.stanford.nlp.pipeline.StanfordCoreNLPServer");
p.waitFor();
}
catch (IOException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
// how to write the statement?
if you want to close command prompt:
Runtime.getRuntime().exec("taskkill /IM " + "cmd.exe");
if you want to close stanford.exe:
Runtime.getRuntime().exec("taskkill /IM " + "stanford.exe");
I need to execute mysql command by Java and write out the result.
But, only empty file created.
Execution environment is MacOS 10.11.2.
public class Main {
public static void main(String[] args) {
String[] cmd = new String[]{"/bin/sh", "-c", "mysql", "-u", "root", "-ppassword", "databaseName"};
ProcessBuilder builder = new ProcessBuilder(cmd);
builder.redirectInput(ProcessBuilder.Redirect.from(new File("sample.sql")));
builder.redirectOutput(new File("result.tsv"));
try {
Process p = builder.start();
p.waitFor();
System.out.println(builder.redirectInput());
} catch (IOException | InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
sample.sql select * from sample;
when the main method executed, displayed redirect to read from file "sample.sql" on console.
And, result.tsv is still empty.
If I input mysql -u root -ppassword -D sql2xlsx < sample.sql > result.tsv into Terminal.app directly,
result.tsv is not empty, and writed expected results.
When my Java program is halted abnormally, applications started by Runtime.exec() do not stop. How do I stop these applications?
Process process = null;
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable()
{
public void run() {
process.destroy();
}
}));
try
{
process = Runtime.getRuntime().exec("win.exe");
process.waitFor();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
process.destroy();
}
addShutdownHook does not execute on forced shutdown of Java such as:
killing from Task Manager
killing via Eclipse Stop button
kill -9 on Linux.
It does execute when using
Ctrl+c
other user initiated interruptions such as Windows shutdown.
kill on Linux
You can test this by compiling your Java file into a class file, then running on the command line. After running on the command line, you can press Ctrl+c to observe that the shutdown hook is executed.
To test, create RunTimeTest.java as shown below, then compile using your JDK.
For example:
"c:\Program Files\Java\jdk1.7.0_40\bin"\javac RunTimeTest.java
"c:\Program Files\Java\jdk1.7.0_40\bin"\java RunTimeTest
Test code:
import java.io.IOException;
import java.util.Arrays;
public class RunTimeTest {
public static void main(String arguments[]) {
ProcessBuilder processBuilder = new ProcessBuilder(Arrays.asList("notepad.exe"));
Process process = null;
try {
process = processBuilder.start();
final Process processToKill = process;
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
#Override
public void run() {
System.out.println("Shutdown Hook");
processToKill.destroy();
}
}));
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
} finally {
if (process != null) {
System.out.println("End of try");
process.destroy();
}
}
}
}
See Javadoc for Runtime
Worst case scenario: if you are using the program multiple times, in the next run you can kill that process.
String command = "cmd /c taskkill /f /im win.exe";
Runtime.getRuntime().exec(command);
I am executing a self-defined command like following code.I know that append a >nul to command will prevent from outputing error or other message to console.But in my code,>nul is treated as a parameter of my own command deletefile.So the command can not execute as expected.How to resolve it?
Runtime runtime = Runtime.getRuntime();
try {
Process p = runtime.exec("deletefile /name:\"ABC\" /owner:\"Wolfman\" >nul");
int status = p.waitFor();
System.out.println(status);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
Solution is:
cmd deletefile /name:\"ABC\" /owner:\"Wolfman\" >nul