如何让 shutdown hook 在从 Eclipse 启动的进程上执行

发布于 2024-07-13 19:34:42 字数 300 浏览 4 评论 0原文

我的应用程序中有一个关闭挂钩(使用 Runtime.getRuntime().addShutdownHook 创建)。 但是,如果我从 Eclipse 中启动该应用程序,当它关闭时,关闭挂钩不会执行。

我认为这是因为 Eclipse 向进程发送了相当于强制终止信号的信号,这不会导致关闭挂钩执行(相当于 Windows 上的 taskkill /F 或 Linux 上的kill -p),尽管我'我不太确定。

有谁知道如何解决这个问题? 我运行的是 Windows (Vista),我感觉这可能是 Windows 特定的问题,但我不确定。

I have a shutdown hook in my application (created using Runtime.getRuntime().addShutdownHook). However if I launch the application from within Eclipse, when it is shut-down the shutdown hook doesn't execute.

I think this is because Eclipse sends the equivalent of a force-kill signal to the process, which doesn't cause the shut-down hook to execute (equivalent of taskkill /F on Windows or kill -p on Linux), though I'm not absolutely sure.

Does anyone know how to get around this? I'm running Windows (Vista), and I've a feeling it may be a Windows-specific issue, but I'm not sure.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

伊面 2024-07-20 19:34:42

我在主要方法的末尾使用了以下 hack 来解决这个问题:

if (Boolean.parseBoolean(System.getenv("RUNNING_IN_ECLIPSE"))) {
    System.out.println("You're using Eclipse; click in this console and " +
            "press ENTER to call System.exit() and run the shutdown routine.");
    try {
        System.in.read();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.exit(0);
}  

I used the following hack at the end of my main method to get around the problem:

if (Boolean.parseBoolean(System.getenv("RUNNING_IN_ECLIPSE"))) {
    System.out.println("You're using Eclipse; click in this console and " +
            "press ENTER to call System.exit() and run the shutdown routine.");
    try {
        System.in.read();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.exit(0);
}  
吲‖鸣 2024-07-20 19:34:42

首先,您的申请是结束还是强制结束? 如果您强行结束它(通过停止按钮),此 Eclipse bug 报告 详细说明了为什么这可能不起作用。

如果做不到这一点,您关于这是 Windows 特定行为的看法可能是正确的。 我使用的是 Mac,所以无法确认,抱歉。 不过,我可以告诉您,以下测试程序确实按预期执行关闭挂钩。

public class MyShutdownHook
{
    public static void main( String[] args )
    {
        System.out.println( "Entering main." );

        Runtime.getRuntime().addShutdownHook( 
            new Thread(
                new Runnable() {
                    public void run() {
                        System.out.println( "Shutdown hook ran." );
                    }   
                }
            )
        );

        System.out.println( "Exiting main." );
    }
}

运行时的 Javadocs #addShutdownHook 确实提到,当 JVM 中止而不是正常退出时,关闭挂钩不会运行,因此,您的假设可能是正确的。 话虽如此,这里有一些可以尝试的事情。 再次抱歉,我无法提前确认这些 - 这里没有 Windows。 (幸运的是!)

  • 确保 JVM 不包含 -Xrs 选项。 这对关闭挂钩有副作用
  • 尝试使用-server-client选项启动JVM。 根据我的经验,边缘情况行为可能会受到 VM 模式选择的影响。 (特别是关于线程——至少在 Mac 上。)
  • 您是否在分析器或类似工具下启动您的应用程序? 加载任何本机库?
  • 您是否遇到了一些致命错误并且错过了它? 例如,OutOfMemoryError 之类的?
  • 尝试在 Eclipse 中应用程序的运行配置对话框中选中/取消选中在后台启动选项。
  • 最后但并非最不重要的一点是:如果有机会,请手动调用System.exit()。 :)

First off, is your application ending or are you forcibly ending it? If you are forcibly ending it (via the stop button), this Eclipse bug report has details about why this might not be working.

Failing that, you may be correct about this being Windows-specific behavior. I'm on a Mac so I can't confirm, sorry. However, I can tell you that the following test program does execute the shutdown hooks as expected.

public class MyShutdownHook
{
    public static void main( String[] args )
    {
        System.out.println( "Entering main." );

        Runtime.getRuntime().addShutdownHook( 
            new Thread(
                new Runnable() {
                    public void run() {
                        System.out.println( "Shutdown hook ran." );
                    }   
                }
            )
        );

        System.out.println( "Exiting main." );
    }
}

The Javadocs for Runtime#addShutdownHook do mention that shutdown hooks do not run when the JVM is aborted, not exited normally, so again, you are probably correct in your assumptions. That being said, here are some things to try. Again, sorry I can't confirm these ahead of time -- no Windows here. (Blessedly!)

  • Make sure the JVM does not include the -Xrs option. This has a side-effect on shutdown hooks.
  • Try launching the JVM using either the -server or -client option. It's been my experience that edge-case behavior can be effected by the choice of VM mode. (Especially with regard to threading -- at least on Mac.)
  • Are you launching your app under a profiler or the like? Loading any native libraries?
  • Are you getting some fatal error and missing it? E.g., OutOfMemoryError or the like?
  • Try checking/unchecking the Launch in background option from your application's Run Configuration dialog in Eclipse.
  • Last but not least: Invoke System.exit() manually if you have the opportunity. :)
流年已逝 2024-07-20 19:34:42

下面是一个可以在 Eclipse 外部运行的脚本,用于列出 Eclipse 下运行且可以终止的可用进程。

#!/bin/bash
set -o nounset                              # Treat unset variables as an error

PROCESSES=$(ps axo pid,ppid,command)

# Find eclipse launcher PID
LAUNCHER_PID=$(echo "$PROCESSES" | grep "/usr/lib/eclipse/eclipse" |grep -v "launcher"|awk '{print $1}')
echo "Launcher PID $LAUNCHER_PID"

# Find eclipse PID
ECLIPSE_PID=$(echo "$PROCESSES" | egrep "[[:digit:]]* $LAUNCHER_PID " | awk '{print $1}')
echo "Eclipse PID $ECLIPSE_PID"

# Find running eclipse sub-process PIDs
SUB_PROCESS=$(echo "$PROCESSES" | egrep "[[:digit:]]* $ECLIPSE_PID " | awk '{print $1}')

# List processes
echo
for PROCESS in $SUB_PROCESS; do
    DRIVER=$(ps --no-headers o pid,ppid,command $PROCESS | awk '{print $NF}')
    echo "$PROCESS $DRIVER"
done

echo "Kill a process using: 'kill -SIGTERM \$PID'"

Here's a script that you can run outside of eclipse to list the available processes running under Eclipse that you could kill.

#!/bin/bash
set -o nounset                              # Treat unset variables as an error

PROCESSES=$(ps axo pid,ppid,command)

# Find eclipse launcher PID
LAUNCHER_PID=$(echo "$PROCESSES" | grep "/usr/lib/eclipse/eclipse" |grep -v "launcher"|awk '{print $1}')
echo "Launcher PID $LAUNCHER_PID"

# Find eclipse PID
ECLIPSE_PID=$(echo "$PROCESSES" | egrep "[[:digit:]]* $LAUNCHER_PID " | awk '{print $1}')
echo "Eclipse PID $ECLIPSE_PID"

# Find running eclipse sub-process PIDs
SUB_PROCESS=$(echo "$PROCESSES" | egrep "[[:digit:]]* $ECLIPSE_PID " | awk '{print $1}')

# List processes
echo
for PROCESS in $SUB_PROCESS; do
    DRIVER=$(ps --no-headers o pid,ppid,command $PROCESS | awk '{print $NF}')
    echo "$PROCESS $DRIVER"
done

echo "Kill a process using: 'kill -SIGTERM \$PID'"
[浮城] 2024-07-20 19:34:42

在 Windows 上,要以标准方式正常停止 Java 应用程序,您需要向其发送 Ctrl + C 。 这仅适用于控制台应用程序,但 Eclipse 使用 javaw.exe 而不是 java.exe。 要解决此问题,请打开启动配置、JRE 选项卡并选择“替代 JRE:”。 将出现“Java 可执行文件”组框,并允许输入备用可执行文件“java”。

现在我们需要一个外部程序将 Ctrl-C 发送到具有隐藏控制台的进程。 我在此处找到了提示在这里。 我们的程序附加到所需进程的控制台并发送控制台事件。

#include <stdio.h>
#include <windows.h>

int main(int argc, char* argv[])
{
    if (argc == 2) {
        unsigned pid = 0;
        if (sscanf_s(argv[1], "%u", &pid) == 1) {
            FreeConsole(); // AttachConsole will fail if we don't detach from current console
            if (AttachConsole(pid)) {
                //Disable Ctrl-C handling for our program
                SetConsoleCtrlHandler(NULL, TRUE);
                GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0);
                return 0;
            }
        }
    }

    return 1;
}

测试java程序:

public class Shuthook {

    public static void main(final String[] args) throws Exception {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                System.out.println("Shutting down...");
            }
        });

        String sPid = ManagementFactory.getRuntimeMXBean().getName();
        sPid = sPid.substring(0, sPid.indexOf('@'));

        System.out.println("pid: " + sPid);
        System.out.println("Sleeping...");
        Thread.sleep(1000000);
    }

}

终止它:

C:\>killsoft.exe 10520

在Eclipse中测试程序输出:

pid: 10520
Sleeping...
Shutting down...

On Windows to gracefully stop a java application in a standard way you need to send Ctrl + C to it. This only works with console apps, but Eclipse uses javaw.exe instead of java.exe. To solve this open the launch configuration, JRE tab and select "Alternative JRE:". The "Java executable" group box appears and allows to enter the alternate executable "java".

Now we need an external program to send Ctrl-C to a process with a hidden console. I found hints here and here. Our program attaches to the console of the desired process and sends the console event.

#include <stdio.h>
#include <windows.h>

int main(int argc, char* argv[])
{
    if (argc == 2) {
        unsigned pid = 0;
        if (sscanf_s(argv[1], "%u", &pid) == 1) {
            FreeConsole(); // AttachConsole will fail if we don't detach from current console
            if (AttachConsole(pid)) {
                //Disable Ctrl-C handling for our program
                SetConsoleCtrlHandler(NULL, TRUE);
                GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0);
                return 0;
            }
        }
    }

    return 1;
}

Test java program:

public class Shuthook {

    public static void main(final String[] args) throws Exception {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                System.out.println("Shutting down...");
            }
        });

        String sPid = ManagementFactory.getRuntimeMXBean().getName();
        sPid = sPid.substring(0, sPid.indexOf('@'));

        System.out.println("pid: " + sPid);
        System.out.println("Sleeping...");
        Thread.sleep(1000000);
    }

}

Terminating it:

C:\>killsoft.exe 10520

Test program output in Eclipse:

pid: 10520
Sleeping...
Shutting down...
七颜 2024-07-20 19:34:42

我不知道如何解决这个问题,但 IntelliJ 在其“运行”对话框中添加了一个单独的按钮,它将以调用关闭挂钩的方式关闭虚拟机。 他们的调试器没有这个功能。

I'm not sure how to fix this but IntelliJ added a separate button to their 'Run' dialog which will shutdown the VM in a way that calls the Shutdown Hooks. Their debugger does not have this feature.

墟烟 2024-07-20 19:34:42

我现在被困在 websphere 中,看不到我在找什么。
但我确实记得 eclipse 有一个与在同一虚拟机中启动应用程序相关的运行配置选项。
您是否可以在与 eclipse VM 相同的 VM 中启动 java 应用程序?

但这个选择却让我忘记了。

I'm stuck in websphere at the moment, and don't see what I'm looking for.
But I do remember eclipse having a run configuration option related to launching the application in the same VM.
Is it possible your launching your java application in the same VM as the eclipse VM?

But the option slips my mind.

情愿 2024-07-20 19:34:42

Sairam就在这里,通过调用System.exit(0)我们可以终止eclipse JVM并可以看到Shutdown hook结果

Sairam is right here, By calling System.exit(0) we can terminate eclipse JVM and can see Shutdown hook results

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文