본문 바로가기

개발 개발/자바

java에서 타 프로그램 실행후 바로 종료 할려면..

But first I had to go through a buttload of pain using JNI, which I 
THOUGHT would be the best bet. 

Then I realized where the solution lies. The first app that uses this update
utility I'm writing will be a program that presents a popup menu in
the Windows system tray and allows you to open URLs and documents and launch
programs from it. Well, the main app calls RUNDLL32.EXE, a Windows program 
that lets you call DLL functions from the command line or a batch file, and
uses RUNDLL32 to call ShellExec.

ShellExec is a Windows library call that launches an app. Or you can pass it a
URL or the path to a document, and if a default app or handler is registered
for the type of URL or document you're opening, it'll automatically open it
(for example, http:// URLs would, by default, open in the default web 
browser, and .doc files open in Microsoft Word by default).

ShellExec creates a new process where the new app will run, and exits 
immediately. It's perfect!

public void launch(String path) {
String commandLine = "rundll32 shell32.dll,ShellExec_RunDLL " + path;
String[] args = commandLine.split(" ");
ProcessBuilder pb = new ProcessBuilder(args);
try {
pb.start();
} catch (Exception exc) {
JOptionPane.showMessageDialog(null, exc.getMessage(),
"Can't launch file/program", JOptionPane.ERROR_MESSAGE);
}
}

A call to launch() followed by a System.exit(0) works EXACTLY the way I 
want it to work.

For Linux/FreeBSD/OS X, what I'll probably do is write a small C program
that forks a new process and uses execl, and call it this way. I can write
that program in such a way that it will be uber-portable.

Thanks to everyone for the suggestions.