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.
I'm guessing you don't have control over the other two apps... If you did, this wouldn't be too bad--you could just have them listen to a socket and see if the socket is available when you come up.
The next solution may actually be language independent. You could manage the whole system through batch file wrappers. Write a batch file that creates a file when it starts up and deletes it when it stops. Unix systems use this technique a lot--they call the file a lock file more often than not.
If only your app will ever start these other apps, then you could simply track if you've started it or not, so I'm guessing this isn't possible or you wouldn't be asking, so I'm assuming that the user may have launched these programs through some other mechanism.
If you have NO control over the launching of the other apps and can't even write a batch file to launch them, then you just can't do what you want to do (Note, the apps would have to always use the batch file, even if the user started them by hand).
I just a very-last ditch effort might be to get a process status and parse it, but you'd have to know exactly what the other apps were called in the PS, this isn't really trivial. Also, all java apps tend to have the same exact signature in most process status printouts which could make this useless.
The problem is that if one of these programs were started outside your app, you have virtually NO WAY to identify that fact unless you happen to know it's exact process status signature, and even then it's flaky.