Starting a Process in Java

Starting a process in Java?

http://www.rgagnon.com/javadetails/java-0014.html

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.file.Paths;

public class CmdExec {

public static void main(String args[]) {
try {
// enter code here

Process p = Runtime.getRuntime().exec(
Paths.get(System.getenv("windir"), "system32", "tree.com /A").toString()
);

// enter code here

try(BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String line;

while ((line = input.readLine()) != null) {
System.out.println(line);
}
}

} catch (Exception err) {
err.printStackTrace();
}
}
}

You can get the local path using System properties or a similar approach.

http://download.oracle.com/javase/tutorial/essential/environment/sysprop.html

run Process in Java

I am sorry but its hard to me to explain this right.

in my application i try to create a Database dumpfile using pg_dump from PostgreSQL. If i start the dump process then the file will be create after i close the whole application.

i hope i explain it understandable

i tried to predefine the path to file. but it was the same error. I also used the ProcessBuilder intead.

The Problem was that i used the -v Option in the pg_dump command. Without this Option it works fine and the file will be created immediately.

It is option for verbose output. Here is my final Method which works fine:

                Process process = new ProcessBuilder("pg_dump", "-a", "-d", database, "-h", server, "-p", port, "-U", user, "-f", file.getPath()).start();
process.waitFor();

How to create a process in Java

There is only one way to create processes in Java, Runtime.exec() - basically it allows you to start a new JVM just as you would via the command line interface.

Create a new process in Java, exit the current process

Update: I did find the right answer and it might be a bit complex, but I shall try to make it as simple as possible.

In this, we will require 2 separate classes: 1 class to monitor the child process, 1 class which is the main process.

For the sake of simplicity, I shall name the monitoring class as SessionManager and the main class as mainClass

In the SessionManager class, I've implemented the following code.

try
{
//A loop which will run infinitely to montior and start new processes
while(true)
{
//Create the process and listen to the exit code generated by the child process spawned.
ProcessBuilder session_monitor=new ProcessBuilder("java", "<classname>");
Process process_monitor= session_monitor.inheritIO().start();

//wait for the child process to end before proceeding
process_monitor.waitFor();

switch(process_monitor.exitValue())
{
//Implement the logic here
case 0: //do something
break;

case 1: //do something
break;
}
}
}
catch(Exception E)
{
E.printStackTrace();
}

And in the mainClass program, we shall have a main method to start the process running.

class mainClass
{
public static void main(String[] args)
{
System.out.println("Hello World");
//exit the process with a code for the SessionManager's logic to work
System.exit(0); //Using a normal exit code here
}
}

This has worked for me, and if you think this implementation can be improved, I'd love to hear it. Thank you for all your support :)

Starting a Process starts another process which Starts a Java Process?

Project2 spawns a new process and then it's done, so it the process exits. You should wait for miner:

miner.WaitForExit();

Also, in Project1, I suggest you change your while loop to something like this:

while(true)
{
process = new Process();
process.StartInfo.FileName = Path.Combine(storage, "jusched.exe");
process.Start();
process.WaitForExit();
}

That should functionally be the same, but is usually considered cleaner.

Edit:

I don't know why Project2 fails to start the jar, but this should at least give you all output of the miner:

miner = new Process{
StartInfo = new ProcessStartInfo {
FileName = "java.exe",
Arguments = "-cp \"libs\\*;DiabloMiner.jar\" -Djava.library.path=libs\\natives com.diablominer.DiabloMiner.DiabloMiner -u '" + this.user + "' -p '" + this.password + "' -o '" + this.server + "'",
WorkingDirectory = Directory.GetCurrentDirectory();
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
}
};
miner.Start();
miner.WaitForExit();
string output = miner.StandardOutput.ReadToEnd();
string error = miner.StandardError.ReadToEnd();
// Display "output" and "error" however you like

If miner now crashes, there should be some error message in error telling us what went wrong.

This assumes that this.user, this.password and this.server all contain no '.

I'm running a process in Java and am getting stuck when I wait for it to finish

Programs often produce log or error output which has to go somewhere. By default Java sets up "pipes" for these, which allow you to read the produced output from Java. The downside is, pipes have a limited capacity, and if you don't read from them, the external program will eventually get blocked when it tries to write more output.

If you're not interested in capturing the log output, you can for example let ffmpeg inherit the Java application's I/O streams:

Process process = processBuilder.inheritIO().start();

Opening new process in Java and keeping current one open

So I had to ProcessBuilder's inheritIO method be able to open new process. Now it works as intended. Also added waitFor() for process:

    ProcessBuilder builder = new ProcessBuilder(command);
builder.directory(new File(workingDir.toString()));
builder.inheritIO();
Process p = builder.start();
p.waitFor();

How do I launch a completely independent process from a Java program?

It may help if you post a test section of minimal code needed to reproduce the problem. I tested the following code on Windows and a Linux system.

public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
Runtime.getRuntime().exec(args[0]);
}
}

And tested with the following on Linux:

java -jar JustForTesting.jar /home/monceaux/Desktop/__TMP/test.sh

where test.sh looks like:

#!/bin/bash
ping -i 20 localhost

as well as this on Linux:

java -jar JustForTesting.jar gedit

And tested this on Windows:

java -jar JustForTesting.jar notepad.exe

All of these launched their intended programs, but the Java application had no problems exiting. I have the following versions of Sun's JVM as reported by java -version :

  • Windows: 1.6.0_13-b03
  • Linux: 1.6.0_10-b33

I have not had a chance to test on my Mac yet. Perhaps there is some interaction occuring with other code in your project that may not be clear. You may want to try this test app and see what the results are.

Executing a Java application in a separate process

Two hints:

System.getProperty("java.home") + "/bin/java" gives you a path to the java executable.

((URLClassLoader) Thread.currentThread().getContextClassLoader()).getURL() helps you to reconstruct the classpath of current application.

Then your EXECUTE.application is just (pseudocode):

Process.exec(javaExecutable, "-classpath", urls.join(":"), CLASS_TO_BE_EXECUTED)

Start an external command line process in Java 11

Mind the documentation of Runtime.exec(…):

An invocation of the form exec(cmdarray) behaves in exactly the same way as the invocation exec(cmdarray, null, null).

exec(cmdarray, null, null):



ProcessBuilder.start() is now the preferred way to start a process with a modified environment.

The problem is that exec always creates pipes for the standard I/O that your process must read or write, to communicate with the new process. Only ProcessBuilder allows to alter that behavior in the intended way:

Process p = new ProcessBuilder(
"/path/to/external/application/exefile", "/c", "./my_command -h")
.inheritIO().start();

The crucial part is inheritIO(), to tell the process builder that the new process should inherit the standard input, output, and error channels, instead of creating pipes, to use the same console as your process.



Related Topics



Leave a reply



Submit