Windows 8/10 API Detect suspended process - windows

UWP (or "Metro") apps in Windows 8/10 are frequently suspended when they are not in the foreground. Apps in this state continue to exist but no longer consume CPU time. This change seems to have been introduced to improve performance on low-power/storage devices like tablets and phones.
Please can I ask, what is the most elegant and simple method to detect an app in this state?
I can see 2 possible solutions at the moment:
Call NtQuerySystemInformation() and the enumerate each process and each thread. A process is "suspended" if all threads are in the suspended state. This approach will require a lot of code and critically NtQuerySystemInformation() is only semi-documented and could be removed in a future OS. NtQueryInformationProcess() may also offer a solution with the same problem.
Call GetProcessTimes() and record the counters for each process. Wait some time (minutes) and check these again. If the process counters haven't changed then assume the process is suspended. This is a hack and I may get shot down for even thinking of it.
Jim

The second one (GetProcessTimes() … wait … and check these again. 
If the process counters haven’t changed then assume the process is suspended)
is less reliable. 
If a process is waiting for input (e.g., keyboard, mouse, or network)
and not getting any, it will use very little CPU time
and will appear to be suspended by this approach.

Related

SC_MONITORPOWER starts background tasks

Summary
When putting the monitor in sleep mode in Windows 10, Windows seems to execute some tasks that don't get executed with the screen on.
This is interfering with our software, and we need to get rid of it.
Ful story
For a hardware device with a touch screen, I need to be able to turn off the touch screen when it's not in use, for durability reasons. Windows has a message that you can send to turn it off, SC_MONITORPOWER. More specifically:
SendMessage(hwnd, WM_SYSCOMMAND, SC_MONITORPOWER, 2);
This works fine, but when the screen is off, Windows is apparently sometimes performing some tasks that it doesn't do when the screen is on. We are careful to never write anything to the screen in this situation (that causes huge problems when the screen is off, in fact just having a blinking cursor in a DOS box is using up half a core when the screen is off).
Our software requires a callback to be executed every 0.25 ms. We have turned nearly every task, service and several other things in Windows off, and with the screen on, I can run our software for days without ever missing a callback. But with the screen off I get hiccups. The callback already runs at the highest possible priority.
So there is apparently something that we missed when we turned all services and tasks off. There appear to be 2 causes of hiccups:
One happens once every 10-30 hours or so (not sure of the exact time, it seems to vary). But it always happens 5 times, with EXACTLY 5 minutes (at most a few milliseconds off) in between (so in total it happens 5 times in a 25 minute period).
Beside this, we get a single hiccup typically every 4-10 hours, but the time between occurrences doesn't seem to be very constant so there could also be multiple causes.
I'm a bit at a loss here, and running analysis software can easily interfere with our own software, making it harder to detect when these hiccups really occur and when they are caused by running the analysis software.
Interestingly, I have seen this 5-times-every-5-minutes thing also on a completely different system (different hardware, different OS version), when recording audio in Adobe Audition. Audition misses pieces of audio every 5 minutes in this case, and I think it also only happens when the monitor is in sleep mode and you're not logged in remotely.
We have already tried to turn the touch screen off using direct monitor commands like Nircmd does, and it doesn't support those. My guess is that the SC_MONITORPOWER message is triggering more things in Windows, and if we can turn them off, that would fix our problem. Any ideas?
System
Intel i5-8700 with 6 cores, Windows LTSB, no extra software installed except our own.
Never mind, problem solved. It was not an extra task that was being started, it was one of the existing Windows processes that for some reason only causes issues when the display is off. Since killing them is not an option (Windows will just restart them), I've suspended the following processes, and the culprit is one of these (I don't know which one yet):
sihost.exe
igfxEM.exe (I very much suspect this one)
RuntimeBroker.exe
dllhost.exe
taskhostw.exe
explorer.exe
I have to continue testing a bit longer to be absolutely certain, but so far with these tasks all suspended I've not seen a missed callback in the last 38 hours. I don't know yet if there are any drawbacks to suspending all these things, so I'll try to find the cause(s) and suspend only that/those.

Windows 7: poor GUI response in my program while downloading data; is there some way to improve this?

I've written a program that (among other things) downloads multiple large files from a server on the LAN, using TCP. This program runs fine under Linux, MacOS/X, and generally under Windows as well (it uses Qt for the GUI and straight sockets calls for networking), but on certain Windows machines the download appears to be too much for the machine to handle, and I'm wondering if anyone has any ideas as to why that is and what can be done about it.
When downloading files, my program spawns a separate I/O thread that basically just sits in a loop, downloading data over TCP and writing it to a file, writing 128KB per call to QFile:write(). Each file is typically several hundred megabytes long, and a typical download session writes out several dozen of these files. Note that the I/O thread runs independently of the GUI thread, so I wouldn't expect it to affect GUI's performance much if at all -- especially not when running on a multicore PC.
The PC in question is a Core-2Duo Quad Q6600 running at 2.40GHz, with 4GB of RAM. It's running Windows 7 Ultimate SP1, 32-bit. It is receiving data over a Gigabit Ethernet connection and writing it to files on the NTFS-formatted boot partition of the 232GB internal Hitachi ATA drive.
The symptom is that sometimes during a download (seemingly at random) the program's GUI will become non-responsive for 10 to 30 seconds at a time, and often the title bar of the window will have "(not responding)" appended to it. The symptom will then clear up again and the download will proceed normally again. Another symptom is that the desktop is extremely sluggish during the download... for example, if I click on the "Start" button, the Start menu will take ~30 seconds to populate, instead of being populated near-instantaneously as I would expect.
Note that Task Manager shows plenty of free memory, but it does show short spikes of CPU usage to 100% one one of the 4 cores, at the same time the problems are seen.
The data is arriving over Gigabit Ethernet, and if I have my program just receive the data and throw it away (without writing it to the hard drive), the machine can maintain a constant download rate of about 96MB/sec without breaking a sweat. If I write the received data to a file, however, the download rate decreases to about 37MB/sec, and the symptoms described above start to appear.
The interesting thing is that just for curiosity's sake I added this call to my I/O thread's entry function, just before the beginning of its event loop:
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
When I did that, the "(not responding)" symptoms cleared, but then download speed was reduced to only ~25MB/sec.
So my questions are:
Does anyone know what might be causing the sporadic hangups of the GUI when the hard drive is under a heavy write-load?
Why does lowering the I/O thread's priority cause the download rate to drop so much, given that there are three idle cores on the machine? I would think that even a lower-priority thread would have plenty of CPU available in this situation.
Is there any way to get a maximum download rate without causing Windows' desktop responsiveness and/or my app's GUI responsiveness to suffer problems?
Without seeing any code is hard to answer but this seems to be something related to processors and the fact that your download thread is not leaving any space for other threads to performs other operations.
It seems it never waits and that the driver of the network card is not well written.
Are you sure your thread is entering in an idle state when there is no data incoming?
In OS with a single processor a for (;;) {} will consume 100% cpu and if it talks continuously with the kernel it may stops other processes or other threads for doing that, especially if there is a bug or a very bad behaviour in some network card driver in your case.
Probably putting the thread priority below normal you are asking the OS to use your thread less often, this gives by a magical combination of things that allow things to not hang too much.
Check the code, maybe you are forgetting something?
Check if adding a sleep(0) to force the OS to yield to another thread sometime will make things better, but this is a temporary fix, you should find why your thread is consuming 100% cpu, if it is.

How UI Threading in android works?

If an app is brought to the background what happens to the UI Thread which was running this app?
Will it sleep or get killed?
When the app is back to foreground will the same thread be notified or a new thread will created and associated with the app instance?
I don't know specifically, but you should always program with the possibility that your Activity may be killed at any time that it is not in the foreground. Whether that involves killing the thread every time it enters the background, or causing the thread to sleep and then killing it if the Activity is killed, I don't know. In any case, you must assume it can and will happen, and program accordingly.
It depends on the memory situation. When your application goes into the background, it generally stays running initially. Android does not sleep your thread. It is up to you to stop updating your UI and performing calculations in on onPause.
However in low memory situations Android might kill application when it's the background (especially if you haven't been nice and are using up a load of resources). For this reason you should always save any persistant data in onPause.

what to do when windows goes in dreaded 100% cpu usage zombie mode

happens to me occasionally:
I start my program in visual studio and due to some bug my program goes into 100% cpu usage and basically freezes windows completely.
Only by utter patience requesting the task manager (takes forever to come up and paint itself) I can kill my process.
Do others encounter this too sometimes? Is there a clever trick to get this process down (other than pulling the plug and possible ruining files on the HD)? It now takes 5-10 minutes to kill it properly if the task manager is not accidentally present and I have to request this first
R
p.s. weird that a 'multitasking os' can still allow processes to eat up so much time that nothing else can be done anymore. My program doesn't even bump up it's thread priorities or anything
Check out Process Lasso
"Process Lasso is a unique new technology that will, amongst other things, improve your PC's responsiveness and stability. Windows, by design, allows programs to monopolize your CPU without restraint -- leading to freezes and hangs. Process Lasso's ProBalance (Process Balance) technology intelligently adjusts the priority of running programs so that badly behaved or overly active processes won't interfere with your ability to use the computer!"
http://www.bitsum.com/prolasso.php
I am not affiliated with Bitsum, just a user of their product, and it helps me solve this type of problems.
For what it's worth, I've never see this on either XP 64 or Vista 64, developing C++ apps in Visual Studio. Perhaps an OS upgrade is in order?
Edit: I use Process Explorer as a replacement Task Manager - it wouldn't surprise me if it did a better job of appearing in good time even when there's a rogue process running. And you can use it to boost its own priority.
I usually hit ctrl-alt-delete start the task manager sort by cpu find the offending process and right click and end the process..
task manager usually has enough priority to do this although it may be slow.
I think a shotgun to the head is the only way to be sure.
I generally don't see anything like this happen strictly as a function of an app that's eating 100% CPU. As part of stability / performance testing, I've gotten apps to cause Windows to get very slow, but this is usually done by writing heavily threaded apps (thus causing the O/S scheduler to thrash), or by writing apps that consume all available system memory or resources (much more impactful to the GUI apps than simply one thread that consumes its full share of processor time during its slices).
You say you get this behavior under Visual Studio? VS has a "Pause" button...

What happens to my app when my Mac goes to sleep?

When Mac OS X goes to sleep, due to closing a laptop or selecting "Sleep" from the Apple menu, how does it suspend an executing process?
I suppose non-windowed processes are simply suspended at an arbitrary point of execution. Is that also true for Cocoa apps, or does the OS wait until control returns to the run loop dispatcher, and goes to sleep in a "known" location? Does any modern OS do that, or is it usually safe enough to simply suspend an app no matter what it is doing?
I'm curious, because allowing sleep to occur at any moment means, from the app's perspective, the system clock could suddenly leap forward by a significant amount. That's a possibility I don't usually consider while coding.
Your app is interrupted exactly where it is that moment if the CPU is actually currently executing code of your app. Your app constantly gets execution time by the task scheduler, that decides which app gets CPU time, on which core, and for how long. Once the system really goes to sleep, the scheduler simply gives no time to your app any longer, thus it will stop execution wherever it is at that moment, which can happen pretty much everywhere. However, the kernel must be in a clean state. That means if you just made a call into the kernel (many libC functions do) and this call is not at some safe-point (e.g. sleeping, waiting for a condition to become true, etc.) or possibly holding critical kernel locks (e.g. funnels), the kernel may suspend sleep till this call returns back to user space or execution reaches such a safe-point before it finally cancels your app from the task scheduler.
You can open a kernel port and register for sleep/wake-up events. In that case, your app will receive an event, when the system wants to go to sleep. You have several possibilities. One is to reply to it, that the system may progress. Another one is to suspend sleep; however, Apple says certain events can be suspended at most 30 seconds, after that, the system will just continue, whether your app likes it or not. And finally, you can cancel it; though not all events can be canceled. If the system already decided it will go to sleep, you can only suspend this by at most 30 seconds or allow it at once, you cannot cancel it. However, you can also listen to an event, where the system asks apps, if it is okay to go to sleep now and there you can reply "no", causing a sleep to be canceled.
The difference between "Is it okay to sleep" and "I'm planing on going to sleep" is: The first one is sent if the power saving settings are applied, that is, if the user has not moved the mouse or typed anything for the time configured there. In that case the system will just ask, if sleep is okay. An app like Apple's DVD Player will say "no", because most likely the user watches a DVD and thus doesn't interact with the computer, still no reason to go to sleep. OTOH, if the user closes his Mac Book, apps are not asked, the system will go to sleep for sure and just informs apps, that have now up to 30 seconds to react to it.
Wake-up events can also be quite interesting to catch. E.g. if your system wakes up, open files might be inaccessible (an external drive has been unplugged) or network sockets won't work any longer (network has changed). So you may re-init certain app parts before using them and running into errors that are more or less expected.
Apple's page regarding catching these events.
It depends on your app.
If you are interacting with external systems (think networking or doing something over usb/firewire,etc) then it might be affected. An application running on OSX gets to run for a limited time ( max 10ms ) , after which it is interrupted by the kernel which schedules a new process from the process queue to run on the CPU. This is transparent for the application , which "thinks" that it runs all the time on the CPU. Thus , a transition to sleep is no different - apart from the time jumping ahead.
If you need to be aware that there was a transition to sleep mode please refer to this tech note which details how to receive notifications about the state change : Registering and unregistering for sleep and wake notifications
I believe it will just suspend all apps wherever they happen to be.
Remember, this happens all the time anyway. Applications are constantly suspended and resumed due to context switching. So, really, the clock could jump between any 2 instructions in your app, though usually not in a noticable/significant way.
If the OS waited for the app to return to some main loop you could run into situations where applications cause the sleep to hang. If they're doing a lot of work and not returning to the run loop dispatcher they would prevent the machine from going to sleep. That wouldn't be very good. :)
And if you set the time it also appears to leap forward to the running programs. Nothing special either.
Check out this Wikipedia article. Cavver is correct in stating that things like network connections may time out, and thus those services may be interrupted.

Resources