问题
I do have a running osgi (equinox container) application. It will been started via a bash script. See felix gogo shell
java -jar ... _osgi.jar -console 1234 &
This all works pretty well and I also can stop it via
telnet localhost 1234
<osgi>stop 0
But what I am looking for is how can I embed this into a bash script to stop the osgi application.
I already tried this
echo stop 0 | telnet localhost 1234
but this doesn't work. So if someone has idea how to put this in a bash script, please let me know.
回答1:
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
回答2:
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/
来源:https://stackoverflow.com/questions/32211120/how-to-stop-an-osgi-application-from-command-line