2011-09-10 22 views
1

我创建了一个Java应用程序,其中main方法(程序的开始)启动一个Process对象和一个创建JFrame的MainWindow类的对象。在Java应用程序中查杀进程的问题

public static void main(String[] args) throws Exception { 

File file = new File("./access/run.bat"); 
ProcessBuilder process_builder = new ProcessBuilder("cmd", "/c", file.getName()); 
process_builder.directory(file.getParentFile()); 
Process process = process_builder.start(); 
MainWindow window = new MainWindow(process); 

} 

我想终止已实例化与process.destroy()当窗口被关闭(杀死)的过程。下面是主窗口类的一些代码:

public MainWindow(final Process process) throws TransformerException, ParserConfigurationException, Exception{ 

JFrame mainWindowFrame = new JFrame(); 

*****some code here*****   

mainWindowFrame.addWindowListener(new WindowListener() { 

public void windowClosed(WindowEvent arg0) { 

    process.destroy(); 
    System.exit(0); 
    } 

*****some code here*****  
    } 

} 

当窗口被关闭,不幸的是,这个过程没有被杀...谁能给我这个解释和可能的解决方案?谢谢!!!

回答

1

根据文档here,只有在窗口被丢弃时才调用windowClosed。要做到这一点,你可以调用处置窗口上或设置默认关闭操作:在你的代码,创建JFrame后,添加以下内容:

mainWindowFrame.setDefaultCloseOperation(javax.swing.JFrame.DISPOSE_ON_CLOSE); 

看你的代码后,我建议你的工作方式不同: 在你的听众中,你正在销毁这个过程然后退出。因此,你可以设置deafualt关闭操作退出,然后实施过程中
实施破坏的windowClosing方法:修改主窗口的代码如下:

public MainWindow(final Process process) throws TransformerException, ParserConfigurationException, Exception{ 

JFrame mainWindowFrame = new JFrame(); 
mainWindowFrame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE); 

*****some code here*****   

mainWindowFrame.addWindowListener(new WindowListener() { 

public void windowClosing(WindowEvent arg0) { 

    process.destroy(); 

    } 

*****some code here*****  
    } 

} 
+0

感谢您的建议,但它不仍能正常工作,该进程仍在运行 – Anto

+0

我提到什么会令该方法被调用,这样的destroy()方法被摆在首位执行,因为它不是之前运行。但似乎你的run.bat文件正在启动其他进程,并且这些进程不会被你的进程的destroy()所销毁。检查下面的帖子[这里](http://stackoverflow.com/questions/6356340/killing-a-process-using-java) –

0

的的Javadoc Process类这样说:

The subprocess is not killed when there are no more references 
to the Process object, but rather the subprocess 
continues executing asynchronously. 

There is no requirement that a process represented 
by a Process object execute asynchronously or concurrently 
with respect to the Java process that owns the Process object. 

在互联网上搜索后,它似乎是在自从Java 1.3 Java平台的issue。我发现这个blog entry解释了关于Java中Process的许多问题。

问题是在杀死应用程序后,process成为孤儿。在您的代码中,由于GUI(MainWindow类)具有其自己的线程,因此您正在从GUI中查找Process,因此它不是父代的Process。这是一个家长/孩子的问题。 有两种方法纠正:

  1. 由于主线程是父进程,所以主线程必须调用destroy方法。所以你必须保留对process对象的引用。

  2. 第二种方法是在启动MainWindow时创建该过程。在MainWindow类的参数中,可以传递进程的参数。因此,当调用windowClosed方法时,如果MainWindow关闭,Process将被销毁,因为后者是MainWindow的子项。

+0

这将取决于run.bat做什么。如果其他进程由bat文件启动,则不会被终止。 –