How to stop an OSGI Application from command line

这一生的挚爱 提交于 2019-12-05 10:44:17
Neil Bartlett

Telneting into the Gogo shell seems like an awfully fragile solution. Why not write your application to support standard POSIX signal handling? Then you could simply kill it with kill -s TERM <pid>.

For example the following bundle activator installs a shutdown hook that cleanly shuts down the framework, equivalently to stop 0:

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.launch.Framework;

public class ShutdownHookActivator implements BundleActivator {

    @Override
    public void start(final BundleContext context) {
        Thread hook = new Thread() {
            @Override
            public void run() {
                System.out.println("Shutdown hook invoked, stopping OSGi Framework.");
                try {
                    Framework systemBundle = context.getBundle(0).adapt(Framework.class);
                    systemBundle.stop();
                    System.out.println("Waiting up to 2s for OSGi shutdown to complete...");
                    systemBundle.waitForStop(2000);
                } catch (Exception e) {
                    System.err.println("Failed to cleanly shutdown OSGi Framework: " + e.getMessage());
                    e.printStackTrace();
                }
            }
        };
        System.out.println("Installing shutdown hook.");
        Runtime.getRuntime().addShutdownHook(hook);
    }

    @Override
    public void stop(BundleContext context) throws Exception {
    }

}

NB: if you are in control of the launcher code that starts the OSGi Framework, you should probably install the shutdown hook there rather from a separate bundle.

Update

In bash, the $! variable evaluates to the PID of the last executed background command. You can save this into your own variable for later reference, e.g.:

# Launch app:
java -jar ... &
MY_PID=$!

# Later when you want to stop your app:
kill $MY_PID

You can for instance use expect, if there is no other way than telnet to close the application.

http://www.tamas.io/automatic-scp-using-expect-and-bash/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!