How to abort shutdown in Windows Vista and 7 programatically? - windows-7

In the second example (in the section examples) on this link, there is a description on using WM_QUERYENDSESSION to abort a shutdown. It also states that this does not work on versions of windows later than XP. This is conflicting with the advice given on another question here at stackoverflow. What is the correct answer? I do not have a computer with either so I am unable to test.

Some applications got the WM_QUERYENDSESSION handling wrong (Not passing to DefWindowProc, they incorrectly returned 0 even though they did not intend to block shutdown) and so MS changed it with Vista, you now need to call ShutdownBlockReasonCreate()
#Konamiman: shutdown.exe -a will abort a "scheduled" shutdown yes, but not a "normal" shutdown by someone calling ExitWindowsEx()

If anything else fails, remember that from command line it is shutdown.exe -a; maybe you could invoke this using the Process class.
EDIT. When mentioning the Process class I happily assumed that the question was about .NET programming, now I see that .NET is not mentioned neither in the question nor in the tags. Anyway I believe that there are ways to run executables from other programming environments as well.

Related

Couldn't start vimrun.exe on shutdown on Windows

I wrote the following code in .vimrc to save last session of vim. Normally, it works. But when shutting down Windows, it doesn't work correctly according to the error of failure about starting vimrun.exe.
au VimLeavePre * call xolox#session#auto_save()
The auto_save methods uses vimrun.exe. As you know, it happens because Windows prohibit a new process to start on shutdown.
Is there any way to avoid the failure?
Windows 7 x64
gvim.exe 7.4
Well, there's no arguing with Windows, right?!
As mentioned in the comments, you could move away from the plugin to native :mksession, but you'd lose all the plugin functionality (which I use and like, too).
You could ask the plugin's author for a lightweight auto_save() fallback that doesn't need to shell out.
Or avoid the problem altogether by saving earlier and more frequently. In GVIM, the FocusLost event would work well.

Windows Service started, but process vanished in task manager

I programmed a Windows Service and it is running on a Windows 2000 machine. Sometimes the executable for this service dies, but the Windows service is still listed as "started" in the service manager. In this situation the restart behaviour defined for this service does not take effect.
Of course, the process needs to be debugged, but I am searching right now for a workaround.
How can I avoid this situation? How does the service manager in Windows 2000 determine if a windows 2000 process is still started or not?
That probably means that the service crashed. IIRC, older versions of windows didn't always recover when a service process abnormally terminates. But that was many years ago and my memory may be faulty.
The best way to avoid the situation is to figure out what's causing your service to crash and fix it.
Although Larry, being a Microsoft employee, probably knows better than anyone else, I dare say that you should give ChangeServiceConfig2 with SERVICE_CONFIG_FAILURE_ACTIONS a shot. I've worked on a legacy service that, before I did the refactoring, used to crash a lot. The remedy my predecessors chose was to use the failure action in order to invoke a program that (running under SYSTEM) would then restart the service as if nothing had happened.
All of this only works if your service is running in its own process, which I assumed given the way you describe it. If your service is implemented in a DLL this will not work.
But I wholeheartedly agree with Larry that you should investigate and fix the problem, rather than trying to conceal it. As mentioned above, I fixed the service in question and it's not crashing or very rarely crashing and everyone is happier with that solution ;)

Identify a reboot

Is there any "Boot session ID" or (reliable) "Boot timestamp"?
For an installation I need to detect that a scheduled reboot took place indeed.
I guess I could do a dummy MoveFileEx() with MOVEFILE_DELAY_UNTIL_REBOOT, but i did hope for something easier.
(We have to install a 3rd party package that sometimes behaves erratically after an repair/update. In that state, accessing the device may even lock up the system)
(Windows XP, Vista, 7)
For things like this, WMI (Windows Management Instrumentation) is often a good starting place. I know you can get current uptime directly through it, which may allow you to determine if a machine recently rebooted.
Here is a blog post with some code samples as well:
http://blogs.technet.com/heyscriptingguy/archive/2004/09/07/how-can-i-tell-if-a-server-has-rebooted.aspx
Depending on your implementation language, you probably just want to pull out the query code from the vbscript.
Apparently Windows has the equivalent of "uptime". Here's more info: http://support.microsoft.com/kb/555737
As I understand it, this should tell you how long ago the system was booted. Will that information solve your problem?
You could search the System event log for event 6009 from the EventLog source - this is the first event recorded after each reboot.
I think the best answer has already been given here: Find out if computer rebooted since the last time my program ran?
That seems to be the simplest way. Use GlobalFindAtom() to see if it exists and create it, with GlobalAddAtom(), if it doesn't. It will persist beyond the execution of your program. If your application runs again, and sees that the atom exists, then then it isn't the first run since reboot.
If the computer is restarted, then the atom won't exist, indicating that this is the first run of your program since the reboot.

How to reload a crashed process on Windows

How to reload a crashed process on Windows? Of course, I can run a custom monitoring Win service process. But, for example, Firefox: it doesn't seem to install such a thing, but still it can restart itself when it crashes.
On Vista and above, you can use the RegisterApplicationRestart API to automatically restart when it crashes or hangs.
Before Vista, you need to have a top level exception filter which will do the restart, but be aware that running code inside of a compromised process isn't entirely secure or reliable.
Firefox constantly saves its state to the hard disk, every time you open a tab or click a link, or perform some other action. It also saves a flag saying it shut down safely.
On startup, it reads this all back, and is able to "restore" based on that info.
Structured exception handling (SEH) allows you to catch program crashes and to do something when it happens.
See: __try and __except
SEH can be very dangerous though and could lead to your program hanging instead. Please see this article for more information.
If you write your program as an NT service then you can set the first, second and subsequent failure actions to "Restart the service".
For Windows 2008 server and Windows Vista and Windows 7 you can use the Win32 API RegisterApplicationRestart
Please see my answer here for more information about dealing with different types of program crashes.
If I recall correctly Windows implements at least some subset of POSIX and so "must" have the signal interface (things like SIGKILL, SIGSEGV, SIGQUIT etc.).
I've never done this but on linux, but you could try setting the unexpected termination trap with signal() (signal.h).
From quick scan of docs it seems that very few things can be done while handling signal, it may be possible that even starting a new process is on forbidden list.
Now that I've thought about it, I'd probably go with master/worker pattern, very simple parent thread that does nothing but spawns the worker (that does all the UI / other things). If it does not set a specific "I'm gonna die now" bit but still dies (parent process always gets message / notification that spawned process died) then master respawns the worker. The main theme is keep master very simple and hard to die due to own bugs.

How to pause / resume any external process under Windows?

I am looking for different ways to pause and resume programmatically a particular process via its process ID under Windows XP.
Process suspend/resume tool does it with SuspendThread / ResumeThread but warns about multi-threaded programs and deadlock problems.
PsSuspend looks okay, but I wonder if it does anything special about deadlocks or uses another method?
Prefered languages : C++ / Python
If you "debug the debugger" (for instance, using logger.exe to trace all API calls made by windbg.exe), it appears that the debugger uses SuspendThread()/ResumeThread() to suspend all of the threads in the process being debugged.
PsSuspend may use a different way of suspending processes (I'm not sure), but it is still possible to hang other processes: if the process you're suspending is holding a shared synchronization object that is needed by another process, you may block that other process from making any progress. If both programs are well-written, they should recover when you resume the one that you suspended, but not all programs are well-written. And if this causes your program that is doing the suspending to hang, then you have a deadlock.
I'm not sure if this does the job, but with ProcessExplorer from MS Systernals you can suspend a process.
It's been said here: https://superuser.com/a/155263 and I found it there too.
read here and you also have psutil for python that you can use it like that:
>>> import psutil
>>> pid = 7012
>>> p = psutil.Process(pid)
>>> p.suspend()
>>> p.resume()
I tested http://www.codeproject.com/KB/threads/pausep.aspx on few softwares:
it works fine.
PsSuspend and Pausep are two valid options.
So, after I found about UniversalPauseButton, Googling for this ("windows SIGSTOP"), getting this question as the first search result (thanks Ilia K. your comment did its job), and reading the answers, I went back to checkout the code.
Apparently, it uses undocumented NT kernel and Win32 APIs _NtSuspendProcess, _NtResumeProcess and _HungWindowFromGhostWindow.
PsSuspend, the utility you mentioned and linked to probably uses these APIs, I couldn't verify this, the source code isn't supplied, only executables and a EULA, you can probably figure that out by disassembling the binary but it's against the EULA.
so, to answer your specific question, checkout UniversalPauseButton's main.cpp, basically you call _NtSuspendProcess(ProcessHandle) and _NtResumeProcess(ProcessHandle), ProcessHandle being the handle of the process you want to pause or resume.
I think there is a good reason why there is no SuspendProcess() function in Windows. Having such a function opens the door for an unstable system. You shall not suspend a process unless you created that process yourself.
If you wrote that process yourself, you could use an event (see ::SetEvent() etc. in MSDN) or another kind of messaging to trigger a pause command in the process.

Resources