How to make a C++ Program listen for system commands
Asked Answered
U

2

6

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. Let's say 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?

In short, can you make it listen for certain system commands on the computer and execute system commands in response?

Uncomfortable answered 18/3, 2013 at 13:21 Comment(2)
Windows has all sorts of messages it passes around. One is WM_QUERYENDSESSION. When you get that you could proactively call shutdown -a. Check this page out for more details on API hooking codeproject.com/Articles/2082/API-hooking-revealedScabble
Note that there's no shutdown command at Windows level. There is a Windows program Shutdown.EXE, which knows which fundamental Windows API to call. But it's not the only program which knows this. E.g. Explorer.EXE (responsible for the start menu) knows it as well. So detecting shutdown.EXE would not affect Explorer.EXE shutting down.Glazed
B
1

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. And after all, shutdown.exe is not the only application that can ask Windows to shut down.

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. For sure that will require "administrative" permissions and can even require to write a kernel module.

Brabble answered 18/3, 2013 at 15:36 Comment(0)
G
1

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);
  3. Else, do what you want.

Well, probably there many more sophisticated ways to do that. And I agree with @VladLazarenko's answer; programs like antiviruses keep listening to system commands. But I guess that would require in-depth knowledge of the 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). Good Luck! :)

Gamble answered 9/4, 2013 at 17:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.