I need to start 1-3 external programs in my Java application that have paths defined by the user. I have few requirements:
I don't want the program to execute if it is already running
I don't want any of the programs to steal focus from my Java application
I don't care if any of them fail to start or not. They just need to fail silently.
Here is what I have come up with so far:
ProcessBuilder pb = new ProcessBuilder(userDefinedPath1);
try {
pb.start();
}
catch (Exception e) {
// Something went wrong, just ignore
}
And then I repeat that 3 more times with the other two paths. This starts like I would expect and meets my third requirement just fine, but fails on the first two.
What is the best way to do this?
Edit:
I don't have any control of these other apps. They are third party. Also, they could have been start or stopped by the user manually at any time.
I know the exact names of the executables (e.g. "blah.exe") and they will always be the same, but the paths to the executables won't necessarily be.
Batch file wrappers are not feasible here.
The other apps are not java apps, just plain old Windows executables.
If you want to check the work of java application, run 'ps' command with '-ef' options, that will show you not only the command, time and PID of all the running processes, but also the full listing, which contains necessary information about the file that is being executed and program parameters.
Making an application single instance, can be achieved by using a mutex (Mutual Exclusion Semaphore). A Windows application loads the main form through the Application. Run( ) method. In the Main method, create a new mutex.
In order to avoid potential lock file / crash issues, it is possible to start a server and catch the port collision. These servers are automatically stopped on system shutdown (Even after a crash)
public static ServerSocket ss;
public static void main (String[] args) {
ss = null;
try {
ss = new ServerSocket(1044);
} catch (IOException e) {
System.err.println("Application already running!");
System.exit(-1);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With