如何在本机 Windows 程序中实现终止开关
我们的程序在某些情况下可能会挂起,有没有一种方法可以在不使用任务管理器的情况下通过 Windows 调用搜索并销毁您自己的程序。 将其包含在程序本身中可能没有意义,但作为捆绑的东西没有人会看到。
执行此操作的最佳方法是什么?我需要挖掘多深才能停止我的程序,以及我应该保持多浅以确保不会使操作系统崩溃?
We've got issues with our program potentially hanging in certain situations, is there a way to search and destroy your own program with windows calls without using task manager. It probably wouldn't make sense to include this in the program itself, but as a bundled thing no one would see.
What's the best way to go about doing this, how deep do I need to dig to stop my program and how shallow should I keep to make sure I don't crash the OS?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以创建一个 .bat 文件并放置 Taskkill 命令可强制终止您的应用程序。 该命令看起来像这样:
You could create a .bat file and put a Taskkill command in it to forcefully terminate your application. The command would look something like this:
尽管您可能应该修复它挂起的情况,但您可以让程序自行终止的一种方法是在启动应用程序时生成一个新线程,并让该线程轮询应用程序并在必要时终止它。
终止 Windows 中的线程。
Although you should probably fix the situation in which it hangs, one way you could have the program kill itself is to spawn a new thread when you launch the app, and have that thread poll the application and kill it if necessary.
Killing a thread in windows.
一种选择是编写一个充当看门狗的 Windows 服务。 您可以通过程序的 .exename 找到您的程序,然后您需要某种方法来确定它是否挂起(例如一些简单的进程间通信,甚至客户端/服务器的东西),并在必要时重新启动它。
但这并不是“没有人会看到”。
One option would be to write a Windows Service that serves as a Watchdog. You could find your program by it's .exename and then you need some way to determine if it hangs (for example some simple Inter-Process-Communication or even a Client/Server thing) and restart it if necessary.
That is hardly "no one would see" though.
您可以使用 TerminateProcess 终止进程。 您需要使用 EnumProcesses< 确定目标进程 ID /a> 然后调用OpenProcess获取进程的句柄以便终止它。
You can terminate a process using TerminateProcess. You'll need to determine the target process id using EnumProcesses and then call OpenProcess to obtain a handle to the process in order to terminate it.
您可以使用
EnumProcesses()
函数枚举正在运行的进程。 这将让您搜索进程名称并获取 PID。 通过 PID,您可以打开所需进程的句柄,以便调用TerminateProcess()
来终止挂起的进程。有一个示例说明如何使用
EnumProcesses
。一些伪代码可能类似于:
You can enumerate running processes using the
EnumProcesses()
function. This will let you search for the process name, and get the PID. With the PID, you can open a HANDLE to the process which you need in order to callTerminateProcess()
to kill the hung process.There's an example of how to use
EnumProcesses
on MSDN.Some pseudo-code might look something like:
从 sysinternals 的 pstools 中实现一些东西怎么样?
What about implementing something from the pstools of sysinternals ?