简体   繁体   English

如何使C ++程序侦听系统命令

[英]How to make a C++ Program listen for system commands

I was recently asked how/if possible that one could do this. 最近有人问我如何/是否可能做到这一点。 I am not sure if it is even possible, and I have been searching on it for a while now. 我不确定是否有可能,而且我已经搜索了一段时间。

Basically let's take Windows for example there is a system command to shut down the computer. 基本上以Windows为例,有一个系统命令可以关闭计算机。 Let's say shutdown -s -t 30 -c "Shutdown" 假设shutdown -s -t 30 -c "Shutdown"

Is there a way to write a program which will listen for a shutdown command, and then run shutdown -a in response to abort that command? 有没有办法编写一个程序,该程序将侦听shutdown命令,然后运行shutdown -a以中止该命令?

In short, can you make it listen for certain system commands on the computer and execute system commands in response? 简而言之,您能否让它侦听计算机上的某些系统命令并作为响应执行系统命令?

This is indeed possible. 确实有可能。 Your example, however, is probably not the best one to describe a generic problem. 但是,您的示例可能不是描述一般问题的最佳示例。 There are session events in Windows that applications can listen to, and shutdown is one of them . Windows中有会话事件,应用程序可以监听,并且关闭事件就是其中之一 And after all, shutdown.exe is not the only application that can ask Windows to shut down. 毕竟, shutdown.exe并不是可以要求Windows关闭的唯一应用程序。

In general, however, applications “listening” for commands being executed will have to integrate tightly with the operating system. 但是,一般而言,“监听”正在执行的命令的应用程序必须与操作系统紧密集成。 You can imagine that anti-virus software does exactly that and a lot more in order to prevent execution of “bad” programs. 您可以想象防病毒软件可以做到这一点,甚至更多,以防止执行“不良”程序。 I am not familiar with Windows technology but would imagine hooking the Windows system call that executes binaries is the way to do it. 我不熟悉Windows技术,但可以想象,挂接执行二进制文件的Windows系统调用是实现此目的的方法。 For sure that will require "administrative" permissions and can even require to write a kernel module. 当然,这将需要“管理”权限,甚至可能需要编写内核模块。

You can go this way: 您可以这样:

  1. Check if the program is exiting. 检查程序是否退出。
  2. If yes, then cancel the program exit call and execute system("shutdown -a); 如果是,则取消程序退出调用并执行system("shutdown -a);
  3. Else, do what you want. 否则,做你想做的。

Well, probably there many more sophisticated ways to do that. 好吧,可能有很多更复杂的方法可以做到这一点。 And I agree with @VladLazarenko's answer; 我同意@VladLazarenko的回答; programs like antiviruses keep listening to system commands. 诸如防病毒软件之类的程序会继续监听系统命令。 But I guess that would require in-depth knowledge of the API. 但是我想这需要深入了解API。 This is just a simple way to do that. 这只是一种简单的方法。 If you are not a newbie, then you must visit this link, http://www.codeproject.com/Articles/2082/API-hooking-revealed (from @RedX's comment). 如果您不是新手,则必须访问此链接, http://www.codeproject.com/Articles/2082/API-hooking-revealed (来自@RedX的评论)。 Good Luck! 祝好运! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM