Asked 11 years, 2 months ago. Modified 11 days ago. Viewed k times. Improve this question. This might be a better choice to refrain from a case where the waitFor never returns. In my case i added waitFor before reading output stream and that caused deadlock situation. Add a comment. Sorted by: Reset to default. Highest score default Date modified newest first Date created oldest first.
There are many reasons that waitFor doesn't return. But it usually boils down to the fact that the executed command doesn't quit. This, again, can have many reasons. You need to continually read from the processes input stream to ensure that it doesn't block.
Improve this answer. Joachim Sauer Joachim Sauer k 55 55 gold badges silver badges bronze badges. This answer is correct but it misses a code sample to troubleshoot the problem. Have a look at Peter Lawrey answer for useful code to find out why waitFor doesn't return.
If the process isn't supposed to quit? If you run ls it will quit but what if you start httpd? Yes, that's another reason why waitFor doesn't return. The question is: how do you handle that situation? You want httpd or whatever to stay open.
Peter Lawrey Peter Lawrey k 74 74 gold badges silver badges bronze badges. I'd rather use pb. Toochka Just for information, redirectError is only available since Java 1. Should be the accepted answer I believe, I replaced my code with this and it immediately worked. Thanks Peter. Also from Java doc: java. RollingBoy RollingBoy 2, 1 1 gold badge 13 13 silver badges 8 8 bronze badges. Else, 2 you need one thread to read from Process. Just spent about four hours figuring this out!
In my case I was calling a batch file from Spring that internally opens one editor. My code was hanging even after applying code of process. But when I open input stream as suggested above and close immediately -- problem goes away. So in my case Spring was waiting for stream close signal.
Even though I am using Java 8 auto closable. So long as the method returns a positive number you are guaranteed a read will not block. Hope that helps someone! Slopes Slopes 5 5 silver badges 9 9 bronze badges. When you don't have the rep to comment, don't work around it and comment anyway. Make this an answer on its own and get rep from it! I don't think it is the process. I tried to use the waitFor long,TimeUnit to timeout if something goes wrong and discovered that it was the read the hung.
Which makes the timeouted version require another thread to do the reading There are several possibilities: You haven't consumed all the output on the process's stdout. You haven't consumed all the output on the process's stderr. The process is waiting for input from you and you haven't provided it, or you haven't closed the process's stdin.
The process is spinning in a hard loop. As others have mentioned you have to consume stderr and stdout. Markus Weninger Markus Weninger Vivek Dhiman Vivek Dhiman 6 6 bronze badges. Eduardo Reyes Eduardo Reyes 31 1 1 bronze badge. Sagan Sagan 1, 1 1 gold badge 12 12 silver badges 11 11 bronze badges. Libish Jacob Libish Jacob 4 4 silver badges 8 8 bronze badges. Laurel 5, 12 12 gold badges 29 29 silver badges 54 54 bronze badges.
Govind Govind 1. WaitForExit ; MessageBox. Show "Code continuing" ; Provide a time-out for the shelled application. The following code sample sets a time-out for the shelled application. The time-out for the example is set to 5 seconds. Process Java Platform SE 8 java. The ProcessBuilder.
Constructs a process builder with the specified operating system program and arguments. This is a convenience constructor that sets the process builder's command to a string list containing the same strings as the command array, in the same order. The java. Process class provides methods for performing input from the process, performing output to the process, waiting for the process to complete, checking the exit status of the process, and destroying killing the process. This can be highly confusing the first time, and should be included in any introduction to these APIs.
Show activity on this post. If you start the process from with in your Java application ex. Invoking this method on Process objects returned by ProcessBuilder. String will forcibly terminate the process. Note: The subprocess may not terminate immediately. This method may be chained to waitFor if needed. A thread is alive if it has been started and not yet terminated. The isAlive method returns true if the thread upon which it is called is still running, otherwise it returns false.
Join method is used when you want to wait for the thread to finish. Interview Q. Java Process class. Java Process exitValue Method. This exitValue method of JavaProcess class is used to return the exit value of processes and subprocesses. Waiting for a Process to Complete.
If the worker thread times out I also exit the io threads. First some background info, I came across the issue to have a timeout while running a command because the program that I tried to execute would never print any debug or error information incase of error and would just keep on retrying internally by itself resulting in process stuck because there was never an error or output stream when it was retrying.
As per java 1. So I tried to implement it with the below logic, where we would keep checking the input stream with input. This simple solution worked like a charm compared to all other that existed. You can launch a Thread that sleeps for the time you want and after the sleep changing a boolean that you loop on in your executeCommandLine method.
Something like that not tested nor compiled, this solution is a prototype you should refactor it if it suit you needs :. I know this is really old post; i needed some help with a similar project so I thought I might give some of my code that I worked and ones that work. Stack Overflow for Teams — Start collaborating and sharing organizational knowledge. Create a free Team Why Teams? Learn more. How to add a timeout value when using Java's Runtime.
Ask Question. Asked 13 years, 1 month ago. Modified 2 years, 1 month ago. Viewed 97k times. Sheena James Adams James Adams 7, 20 20 gold badges 81 81 silver badges bronze badges. I take it this is an simplified example. You know this will block if the buffers for standard output or standard error run full. You have read them asynchronously, both in parallel. MichaelPiefel That's true.
So I am starting a new Thread for these, but the question is when process dies, does one have to kill the threads as well? Add a comment. Sorted by: Reset to default. Highest score default Date modified newest first Date created oldest first. I tried this, but I am getting worker. Don't just pose a block of code. Please provide explanations. Perhaps I don't understand Thread.
How does this stop the process executing if the timeout has expired? I've run a test using the above, in which I print the current time to stdout , run the process and then print the time again. The process takes approximately 3s to execute. The process always completes after the timeout period has elapsed, even though I've specified the timeout as 1s and expect to get a TimeoutException.
AgiHammerthief I am relying on Process. I will do some testing. What OS are you running? Did you run your test inside an IDE or from a shell? Show 5 more comments. Community Bot 1 1 1 silver badge. Muzikant Muzikant 8, 5 5 gold badges 52 52 silver badges 85 85 bronze badges. Very useful. I've used this mold because it let me keep my stream consuming threads as-is. However, I've updated the waitForProcess to account for spurious interrupts I don't think it's good to use Interger.
I implemented the utility class I'm using for this with the three methods for executing a command with a timeout like so: package com. BufferedReader; import java. IOException; import java. InputStreamReader; import java. Callable; import java. ExecutionException; import java. Executors; import java. Future; import java. TimeUnit; import java. TimeoutException; import org.
Log; import org. InputStream; import java. InputStreamReader; import org. TimeoutException at java. Mogsdad I don't think you should return from waiting for process exit code on interrupt. This should loop until you successfully got the exit code. May I ask why you use cmd. I tried this but it always throw Timeout exception stackoverflow. The System. Parameters: status - Termination status. By convention, a nonzero status code indicates abnormal termination.
Thread , removeShutdownHook java. The Java virtual machine shuts down in response to two kinds of events: The program exits normally, when the last non-daemon thread exits or when the exit equivalently, System. A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently.
When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt. Note that daemon threads will continue to run during the shutdown sequence, as will non-daemon threads if shutdown was initiated by invoking the exit method. Once the shutdown sequence has begun it can be stopped only by invoking the halt method, which forcibly terminates the virtual machine. Once the shutdown sequence has begun it is impossible to register a new shutdown hook or de-register a previously-registered hook.
Attempting either of these operations will cause an IllegalStateException to be thrown. Shutdown hooks run at a delicate time in the life cycle of a virtual machine and should therefore be coded defensively. They should, in particular, be written to be thread-safe and to avoid deadlocks insofar as possible. They should also not rely blindly upon services that may have registered their own shutdown hooks and therefore may themselves in the process of shutting down.
Attempts to use other thread-based services such as the AWT event-dispatch thread, for example, may lead to deadlocks. Shutdown hooks should also finish their work quickly. When a program invokes exit the expectation is that the virtual machine will promptly shut down and exit. When the virtual machine is terminated due to user logoff or system shutdown the underlying operating system may only allow a fixed amount of time in which to shut down and exit.
It is therefore inadvisable to attempt any user interaction or to perform a long-running computation in a shutdown hook. Uncaught exceptions are handled in shutdown hooks just as in any other thread, by invoking the uncaughtException method of the thread's ThreadGroup object. The default implementation of this method prints the exception's stack trace to System. In rare circumstances the virtual machine may abort , that is, stop running without shutting down cleanly. The virtual machine may also abort if a native method goes awry by, for example, corrupting internal data structures or attempting to access nonexistent memory.
If the virtual machine aborts then no guarantee can be made about whether or not any shutdown hooks will be run. Parameters: hook - An initialized but unstarted Thread object Throws: IllegalArgumentException - If the specified hook has already been registered, or if it can be determined that the hook is already running or has already been run IllegalStateException - If the virtual machine is already in the process of shutting down SecurityException - If a security manager is present and it denies RuntimePermission "shutdownHooks" Since: 1.
Thread , halt int , exit int removeShutdownHook public boolean removeShutdownHook Thread hook De-registers a previously-registered virtual-machine shutdown hook. Parameters: hook - the hook to remove Returns: true if the specified hook had previously been registered and was successfully de-registered, false otherwise. Throws: IllegalStateException - If the virtual machine is already in the process of shutting down SecurityException - If a security manager is present and it denies RuntimePermission "shutdownHooks" Since: 1.
Thread , exit int halt public void halt int status Forcibly terminates the currently running Java virtual machine. This method should be used with extreme caution. Unlike the exit method, this method does not cause shutdown hooks to be started and does not run uninvoked finalizers if finalization-on-exit has been enabled.
If the shutdown sequence has already been initiated then this method does not wait for any running shutdown hooks or finalizers to finish their work. If the exit equivalently, System. Throws: SecurityException - If a security manager is present and its checkExit method does not permit an exit with the specified status Since: 1. Enable or disable finalization on exit; doing so specifies that the finalizers of all objects that have finalizers that have not yet been automatically invoked are to be run before the Java runtime exits.
By default, finalization on exit is disabled. If there is a security manager, its checkExit method is first called with 0 as its argument to ensure the exit is allowed. This could result in a SecurityException.
Parameters: value - true to enable finalization on exit, false to disable Throws: SecurityException - if a security manager exists and its checkExit method doesn't allow the exit. This is a convenience method. An invocation of the form exec command behaves in exactly the same way as the invocation exec command, null, null.
Parameters: command - a specified system command. An invocation of the form exec command, envp behaves in exactly the same way as the invocation exec command, envp, null. An invocation of the form exec command, envp, dir behaves in exactly the same way as the invocation exec cmdarray, envp, dir , where cmdarray is an array of all the tokens in command. More precisely, the command string is broken into tokens using a StringTokenizer created by the call new StringTokenizer command with no further modification of the character categories.
The tokens produced by the tokenizer are then placed in the new string array cmdarray , in the same order. An invocation of the form exec cmdarray behaves in exactly the same way as the invocation exec cmdarray, null, null. Parameters: cmdarray - array containing the command to call and its arguments.
An invocation of the form exec cmdarray, envp behaves in exactly the same way as the invocation exec cmdarray, envp, null. Given an array of strings cmdarray , representing the tokens of a command line, and an array of strings envp , representing "environment" variable settings, this method creates a new process in which to execute the specified command.
This method checks that cmdarray is a valid operating system command. Which commands are valid is system-dependent, but at the very least the command must be a non-empty list of non-null strings. If envp is null , the subprocess inherits the environment settings of the current process. A minimal set of system dependent environment variables may be required to start a process on some operating systems. As a result, the subprocess may inherit additional environment variable settings beyond those in the specified environment.
The working directory of the new subprocess is specified by dir. If dir is null , the subprocess inherits the current working directory of the current process. If a security manager exists, its checkExec method is invoked with the first component of the array cmdarray as its argument. This may result in a SecurityException being thrown. Starting an operating system process is highly system-dependent. Among the many things that can go wrong are: The operating system program file was not found.
Access to the program file was denied. The working directory does not exist. In such cases an exception will be thrown. The exact nature of the exception is system-dependent, but it will always be a subclass of IOException. This value may change during a particular invocation of the virtual machine. Applications that are sensitive to the number of available processors should therefore occasionally poll this property and adjust their resource usage appropriately.
Note that the amount of memory required to hold an object of any given type may be implementation-dependent. Returns: the total amount of memory currently available for current and future objects, measured in bytes. If there is no inherent limit then the value Long. The name gc stands for "garbage collector".
The virtual machine performs this recycling process automatically as needed, in a separate thread, even if the gc method is not invoked explicitly. The method System. Calling this method suggests that the Java virtual machine expend effort toward running the finalize methods of objects that have been found to be discarded but whose finalize methods have not yet been run.
When control returns from the method call, the virtual machine has made a best effort to complete all outstanding finalizations. The virtual machine performs the finalization process automatically as needed, in a separate thread, if the runFinalization method is not invoked explicitly. See Also: Object. If the boolean argument is true , this method suggests that the Java virtual machine emit debugging information for each instruction in the virtual machine as it is executed.
The format of this information, and the file or other output stream to which it is emitted, depends on the host environment. The virtual machine may ignore this request if it does not support this feature. The destination of the trace output is system dependent.
Per the post from RollingBoy, this code almost worked for me: Process process = rtton.xyztime().exec("tasklist"); BufferedReader reader. rtton.xyz › › Java Programming. Opening a new browser using rtton.xyztime().exec(cmd); under windows wait for exit code -- if it's 0, command worked.