如何允许一次只运行一个Java程序实例?

编程入门 行业动态 更新时间:2024-10-09 01:23:57
本文介绍了如何允许一次只运行一个Java程序实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要多次阻止用户启动我的Java应用程序(WebStart Swing应用程序)。因此,如果应用程序已经运行,则无法再次启动它或显示警告/再次关闭。

I need to prevent users from starting my Java application (WebStart Swing app) multiple times. So if the application is already running it shouldn't be possible to start it again or show a warning / be closed again.

是否有一些方便的方法来实现此目的?我想过阻塞一个端口或写一个文件。但希望您可以访问某些系统属性或JVM?

Is there some convenient way to achieve this? I thought about blocking a port or write sth to a file. But hopefully you can access some system properties or the JVM?

btw。目标平台是带有Java 1.5的Windows XP

btw. target platform is Windows XP with Java 1.5

推荐答案

我认为您在启动应用程序时打开端口进行监听的建议是最好的主意。

I think your suggestion of opening a port to listen when you start your application is the best idea.

这很容易做到,关闭应用程序时无需担心清理它。例如,如果你写一个文件,但有人然后使用任务管理器杀死进程,文件将不会被删除。

It's very easy to do and you don't need to worry about cleaning it up when you close your application. For example, if you write to a file but someone then kills the processes using Task Manager the file won't get deleted.

另外,如果我没记错,那么没有从JVM内部获取Java进程的PID的简便方法,所以不要尝试使用PID来制定解决方案。

Also, if I remember correctly there is no easy way of getting the PID of a Java process from inside the JVM so don't try and formulate a solution using PIDs.

这样的事情应该可以解决问题: / p>

Something like this should do the trick:

private static final int PORT = 9999; private static ServerSocket socket; private static void checkIfRunning() { try { //Bind to localhost adapter with a zero connection queue socket = new ServerSocket(PORT,0,InetAddress.getByAddress(new byte[] {127,0,0,1})); } catch (BindException e) { System.err.println("Already running."); System.exit(1); } catch (IOException e) { System.err.println("Unexpected error."); e.printStackTrace(); System.exit(2); } }

此示例代码明确绑定到 127.0.0.1 应避免任何防火墙警告,因为此地址上的任何流量必须来自本地系统。

This sample code explicitly binds to 127.0.0.1 which should avoid any firewall warnings, as any traffic on this address must be from the local system.

选择端口时尽量避免众所周知的端口列表中提到的一个。理想情况下,您应该在文件中使用可配置的端口,或者在发生冲突时通过命令行开关进行配置。

When picking a port try to avoid one mentioned in the list of Well Known Ports. You should ideally make the port used configurable in a file or via a command line switch in case of conflicts.

更多推荐

如何允许一次只运行一个Java程序实例?

本文发布于:2023-11-24 00:45:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1623351.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   程序   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!