- Spawn a process in Java that survives a JVM shutdown
- 7 Answers 7
- Spawn a process in Java that survives a JVM shutdown
- Spawn a process in Java that survives a JVM shutdown
- How can I set the process name for a Java-program? [duplicate]
- Java Getting Started
- Java Install
- Setup for Windows
- Starting a process in Java?
- 3 Answers 3
Spawn a process in Java that survives a JVM shutdown
I need to spawn a process in Java (under Linux exclusively) that will continue to run after the JVM has exited. How can I do this? Basically the Java app should spawn an updater which stops the Java app, updates files and then starts it again. I’m interested in a hack & slash method to just get it working as well as a better design proposal if you have one 🙂
7 Answers 7
If you’re spawning the process using java.lang.Process it should «just work» — I don’t believe the spawned process will die when the JVM exits. You might find that the Ant libraries make it easier for you to control the spawning though.
It does actually «just work», unless you’re trying to be clever.
My wrapped java.lang.Process was trying to capture the script’s output, so when the JVM died, the script didn’t have anywhere to send output so it just dies. If I don’t try to capture the output, or the script doesn’t generate any or redirects everything to a file or /dev/null, everything works as it should.
I was having trouble with this and the launched process was getting killed when the JVM shutdown.
Redirecting stdout and stderr to a file fixed the issue. I guess the process was tied to the launched java app as by default it was expecting to pass its output to it.
Here’s the code that worked for me (minus exception handling):
ProcessBuilder pb = new ProcessBuilder(cmd); pb.redirectOutput(logFile); pb.redirectError(logFile); Process p = pb.start();
I thought the whole point of Java was that it’s fully contained within the JVM. It’s kinda hard to run bytecode when there’s no runtime.
If you’re looking to have a totally separate process you might look into trying to start a second java.exe instance. Although for your application, it might be easier to simply make a synchronized block that stops (but doesn’t kill) your app, does the updating, and then re-initializes your app’s data.
It won’t always «just work». When JVM spawns the child and then shuts down, the child process will also shutdown in some cases. That is expected behaviour of the process. Under WIN32 systems, it just works.
E.g. If WebLogic server was started up by a Java process, and then that process exits, it also sends the shutdown signal to the WebLogic via shutdown hook in JVM, which causes WebLogic to also shutdown.
If it «just works» for you then there is no problem, however if you find yourself in a position that child process also shutsdown with JVM it is worth having a look at the «nohup» command. The process won’t respond to SIGTERM signal, but will respond to SIGKILL signal, as well as normal operations.
Update: The way described above is a bit of an overkill. Another way of doing this would be to use «&» on the end of command. This will spawn a new process that is not a child of current java process.
P.S. Sorry for so many updates, I have been learning and trying it from scratch.
Spawn a process in Java that survives a JVM shutdown
In that case, You will have to add a new path with: C:\Program Files\Java\jdk-11.0.1\bin Then, click «OK», and save the settings At last, open command prompt (cmd.exe) and type java -version to see if Java is running on your machine Show how to install Java step-by-step with images » Step 1 Step 2 » Step 2 Step 3 » Step 3 Step 4 » Step 4 Step 5 » Step 5 Write the following in the command line (cmd.exe): C:\Users\ Your Name >java -version However, it is possible to write Java in an Integrated Development Environment, such as IntelliJ IDEA, Netbeans or Eclipse, which are particularly useful when managing larger collections of Java files.
Spawn a process in Java that survives a JVM shutdown
I need to spawn a process in java (under Linux exclusively) that will continue to run after the JVM has exited. How can I do this?
Basically the Java app should spawn an updater which stops the Java app, updates files and then starts it again.
I’m interested in a hack & slash method to just get it working as well as a better design proposal if you have one 🙂
If you’re spawning the process using java.lang.Process it should «just work» — I don’t believe the spawned process will die when the JVM exits. You might find that the Ant libraries make it easier for you to control the spawning though.
It does actually «just work», unless you’re trying to be clever.
My wrapped java.lang.Process was trying to capture the script’s output, so when the JVM died, the script didn’t have anywhere to send output so it just dies. If I don’t try to capture the output, or the script doesn’t generate any or redirects everything to a file or /dev/null, everything works as it should.
I was having trouble with this and the launched process was getting killed when the JVM shutdown.
Redirecting stdout and stderr to a file fixed the issue. I guess the process was tied to the launched java app as by default it was expecting to pass its output to it.
Here’s the code that worked for me (minus exception handling):
ProcessBuilder pb = new ProcessBuilder(cmd); pb.redirectOutput(logFile); pb.redirectError(logFile); Process p = pb.start();
I thought the whole point of Java was that it’s fully contained within the JVM. It’s kinda hard to run bytecode when there’s no runtime.
If you’re looking to have a totally separate process you might look into trying to start a second java.exe instance. Although for your application, it might be easier to simply make a synchronized block that stops (but doesn’t kill) your app, does the updating, and then re-initializes your app’s data.
How to set java library path for processing, 0. Conclustion of above all answers (short form) is as follows: Lets say my lib folder path is lib/. Then to add in the library path: run below command: java -Djava.library.path=lib/ -jar mySampleJar.jar. Share. Improve this answer. answered Jan 19, 2021 at 9:42. Hafiz Muhammad Shafiq.
How can I set the process name for a Java-program? [duplicate]
If a Java program is started, it get’s in the system process-monitor the name java. Many Java-programs are that way hard to distinguish. So it would be nice, if a way exists, to set the name, that will be shown in the process-monitor. I’m aware that this may work different on different Operating Systems.
A simple way would be, if the java-interpreter would support a switch to set the name, like this:
java -processname MyProgram -jar MyProgram
But I couldn’t find such a switch, so it is probably non-existant. An API in Java to set the process-name would be also fine.
So, so you have any suggestions?
I don’t know if this is possible, but you could use a command line tool that comes with the JDK called ‘jps’. It’s like *nix ps , but just Java programs instead. jps -v shows all the arguments you have passed to java.
Also, I have seen people attach a «process name» to their java processes by adding an unused -Dmyprocessname to the args.
prints out all java processes If the params list is not enough to recognize the applications you need, try adding some dummy params when running them:
java -Dname=myApp -cp myApp.jar some.client.main.MainFrame
7780 MainFrame -Dname=myApp
and you can use the process ID to kill / monitor it.
You can do this with an LD_PRELOAD shim: https://github.com/airlift/procname
The shim simply calls the Linux-specific prctl() when the process starts:
static void __attribute__ ((constructor)) procname_init()
The call has to happen on the main thread, so it isn’t possible to do this from Java or even with a jvmti agent, since those happen on a different thread.
When I first read this, the idea of changing the process name struck me as impossible. However, according to this ancient thread on the sun forum you can use C++ wrappers around the JVM executable to achieve this.
Though frankly, I wonder what your real problem is, as I’d guess there is a more standard solution then attempting to change the process name.
Guide to java.lang.Process API, The Process class provides methods for interacting with these processes including extracting output, performing input, monitoring the lifecycle, checking the exit status, and destroying (killing) it. 2. Using Process Class for Compiling and Running Java Program
Java Getting Started
Java Install
Some PCs might have Java already installed.
To check if you have Java Installed on a Windows PC, search in the start bar for Java or type the following in Command Prompt (cmd.exe):
If Java is installed, you will see something like this (depending on version):
java version «11.0.1» 2018-10-16 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.1+13-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.1+13-LTS, mixed mode)
If you do not have Java installed on your computer, you can download it for free at oracle.com.
Note: In this tutorial, we will write Java code in a text editor. However, it is possible to write Java in an Integrated Development Environment, such as IntelliJ IDEA, Netbeans or Eclipse, which are particularly useful when managing larger collections of Java files.
Setup for Windows
- Go to «System Properties» (Can be found on Control Panel > System and Security > System > Advanced System Settings)
- Click on the «Environment variables» button under the «Advanced» tab
- Then, select the «Path» variable in System variables and click on the «Edit» button
- Click on the «New» button and add the path where Java is installed, followed by \bin . By default, Java is installed in C:\Program Files\Java\jdk-11.0.1 (If nothing else was specified when you installed it). In that case, You will have to add a new path with: C:\Program Files\Java\jdk-11.0.1\bin
Then, click «OK», and save the settings - At last, open command prompt (cmd.exe) and type java -version to see if Java is running on your machine
Starting a process in Java?
Is there an equivalent in Java so I can then let the user find the application and then it would work for any OS?
3 Answers 3
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.
Note that you should use the .exec(String[]) form of the method, not the single string .exec(String) form which is not a command line processor — it simply splits on spaces. They give the same result for this example tree.com /A but are different if given, for example, a filename that has spaces in it.
The Java Class Library represents external processes using the java.lang.Process class. Processes can be spawned using a java.lang.ProcessBuilder :
Process process = new ProcessBuilder("processname").start();
or the older interface exposed by the overloaded exec methods on the java.lang.Runtime class:
Process process = Runtime.getRuntime().exec("processname");
Both of these will code snippets will spawn a new process, which usually executes asynchronously and can be interacted with through the resulting Process object. If you need to check that the process has finished (or wait for it to finish), don’t forget to check that the exit value (exit code) returned by process.exitValue() or process.waitFor() is as expected (0 for most programs), since no exception is thrown if the process exits abnormally.
Also note that additional code is often necessary to handle the process’s I/O correctly, as described in the documentation for the Process class (emphasis added):
By default, the created subprocess does not have its own terminal or console. All its standard I/O (i.e. stdin, stdout, stderr) operations will be redirected to the parent process, where they can be accessed via the streams obtained using the methods getOutputStream(), getInputStream(), and getErrorStream(). The parent process uses these streams to feed input to and get output from the subprocess. 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, or even deadlock.
One way to make sure that I/O is correctly handled and that the exit value indicates success is to use a library like jproc that deals with the intricacies of capturing stdout and stderr, and offers a simple synchronous interface to run external processes:
ProcResult result = new ProcBuilder("processname").run();
jproc is available via maven central:
org.buildobjects jproc 2.5.1