I want to find out whether or not a certain process is sleeping or not (C++/Windows).
I'm trying to use the suspend count to do so and suspending to process before the check for
profiling processes.
I'm doing something like this:
SuspendThread(threadHandle);
... Do Some Stuff ...
int suspended = ResumeThread(threadHandle);
if (suspended > 1)
m_isSleeping = true;
According to MSDN: http://msdn.microsoft.com/en-us/library/ms685086%28v=vs.85%29.aspx
If a process is suspended, "ResumeThread" returns a value > 0.
In my case, the process is a sleeping process, so I'd expect that the suspend count would be [My Call To SuspendThread] + [The "Sleep" method within the process] = 2
but I keep getting: ResumeThread(threadHandle) == 1
Does anybody know why it happens?
thanks :)
A thread in Sleep isn't suspended, hence the return value of 1
You're confusing threads and processes. ResumeThread and SuspendThread do not operate on process handles, they operate on thread handles. Also, Sleep does not change the suspend count of a process, only ResumeThread and SuspendThread change that. If you're trying to detect if a thread is currently in a Sleep call, you're doing it wrong.
in addition to what others said, your SuspendThread call is not guaranteed to suspend thread immediately, it can be running for a time, and you can actually call ResumeThread while thread is still running (see details: http://www.dcl.hpi.uni-potsdam.de/research/WRK/2009/01/what-does-suspendthread-really-do/)
Related
I have a multithreaded application under Windows 7.
I need to correctly finish jobs in threads which have an open descriptors, connections and so on when a user presses 'X' in the corner of command line, 'Ctrl+C', shuts down OS and so on.
I've set a handler for SetConsoleHandler which sets appropriate flags for other threads to correctly finish their job. But all of them are interrupted and the y exit with code 0xc000013a. SOmetimes even my handler doesn't have time to set flag.
The same problem remains when I try to do the same operations in atexit handler.
Why are all threads stopped even during interruption handler? How can I avoid this and let all my threads finish their job?
sets appropriate flags for other threads to correctly finish their job
Usually it's not enough. You also must wait the threads to finish (thread.join(), or WaitForMultipleObjects, or something similar).
The problem in my case was that some of child-children thread used timed-waiting on system resources so each of them needed to wake from waiting to join thread. And all of them were stopping consecutively so they required too much time to stop.
In my program, it start a boost thread and keep the handler as a member of the main thread.
When user press the cancel button I need to check the started thread still running and if it is running need tho kill that specific thread. here is the pseudo code.
cheating thread
int i =1;
boost::thread m_uploadThread = boost::thread(uploadFileThread,i);
This is the method use to check if thread is still running, but it is not working
boost::posix_time::time_duration timeout = boost::posix_time::milliseconds(2);
if (this->uploadThread.timed_join(timeout)){
//Here it should kill the thread
}
The return value true means the thread is completed before the call times out. And looks like what you want is
if(!this->uploadThread.timed_join(timeout))
For stop your thread you can use:
my_thread.interrupt();
in order this to work you have to set an interruption point at the point you want the thread's function stops when you interrupt.
Note: the interruption by it self don't stop the thread it just set a flag and the when an interruption point is reached the thread is interrupted. If no interruption point is found, the thread don't stop.
You can also handle the interrupted exception boost::thread_interrupted that way you can do things depending on if the thread was interrupted or not.
For instance lets assume the next code is inside a thread function:
try
{
//... some important code here
boost::this_thread.interruption_poit(); // Setting interrutption point.
}
catch(boost::thread_interrupted&)
{
// Now you do what ever you want to do when
// the thread is interrupted.
}
How to?
I tried a WaitingForSingleObject, GetExitCodeThread and etc., but when i kill thread with process explorer nothing happens.
while(true)
{
if(GetThreadId(this->hWatchThread) == 0) // Always return killed thread id!
break;
}
Upd:
When i kill thread, it stop working, but i can't get exit code or zero value from GetThreadId
When a thread is killed forcibly, e.g. from the task manager or from Process Explorer, that does not change the thread ID. The thread handle still exists because your process has not yet closed it. And the thread ID associated with that thread still exists. So GetThreadId will always return a non-zero value.
As for the exit code, you can't get a meaningful value for the exit code because the thread did not exit. It was killed. It never had a chance to set an exit code.
What you must do is use one of the wait functions, e.g. WaitForSingleObject, to wait on your thread handle. If that wait terminates because the thread was killed, then the wait function will return and report a successful wait and the thread exit code will be reported as 0. To the best of my knowledge you cannot discern by means of the Windows API that your thread was killed abnormally.
What you could do is use your own mechanism to indicate that termination was abnormal. Create a flag, owned by the thread, to record that termination was normal. Set the flag to false when the thread starts executing. When the thread terminates normally, set the flag to true. This way you can tell whether or not the thread was terminated abnormally by reading the value of that flag after the thread terminates.
If you want to do something after the thread has exited:
WaitForSingleObject(handle_to_your_thread,INFINITE);
MessageBox(NULL,"Thread has exited","Foo",MB_ICONINFORMATION);
I peek into my ancestor's code and found out a leak in the following situation:
1) Launch application
b) After application is launched, close the applicaiton within 4 secs
The leak message:
f:\dd\vctools\vc7libs\ship\atlmfc\src\mfc\thrdcore.cpp(306) : {58509} client block at 0x016DFA30, subtype c0, 68 bytes long.
Subsequently, I went through the code, found out the suspicious point of cause at a 4secs of sleep at controlling function of worker thread.
The test program:
UINT InitThread(LPVOID pParam)
{
Sleep(4000); //4000 is the default value, it reads from a registry key.
CMyMFCTestProjectDlg* pTest = (CMyMFCTestProjectDlg*)pParam;
pTest->DoSomething();
return 0; //--> Exit thread
}
BOOL CMyMFCTestProjectDlg::OnInitDialog() {
...
AfxBeginThread(InitThread, this);
...
}
If I reduce/remove the sleep timer, the leak will be solved.
However, I would like to know how does it happen. Either due to worker thread or GUI thread termination? Will worker thread exits after GUI thread will cause this problem?
Anyone can cheer up my day by helping me to explain this? I'm lost....
It sounds like the worker thread is not given a chance to close itself properly after your app closes, since the process ends before it exits. The operating system is usually pretty good at cleaning up resources on its own, so it may not be a problem. However, it's probably best if you wait for that thread to exit before allowing the application to shut down. Though it sounds like that that will cause a 4 second delay in the shutdown of your app.
If that's unacceptable, you will have to add some mechanism to the thread, to receive the shutdown event from the apps main thread. For example, if you replace the worker threads "sleep", with a WaitForSingleObject of an event:
DWORD res = WaitForSingleObject(
shutdownEvent,
4000); // timeout
if(res == WAIT_OBJECT_0)
{
// received the shutdownEvent, exit
return 0;
}
// The delay has elapsed, continue with rest of thread.
. . .
Then, when your are shutting down in your main thread, set the event, then wait for the thread to exit, it should exit almost immediately:
SetEvent(this->shutdownEvent);
WaitForSingleObject(pThread->m_hThread, INFINITE); // pThread is returned from AfxBeginThread
You should shutdown your threads gracefully before your process goes away. You can either have the main thread wait for the other thread(s) to exit or have the main thread signal the other thread(s) to exit.
68 bytes?
If the application does actually shut down, ie. has disappeared from the task manager 'Applications' and 'Processes', and the only effect of this 'leak' is to issue a debug message on early close, just turn the debug off and forget about it.
It's likely an abberation of MFC shutdown, some struct that cannot be safely freed during shutdown and is left around for the OS to clean up.
With the 99.9% of apps that are not continually restarted/stopped, a 68-byte leak on shutdown, even if it was not cleaned up, would not influence the operation of a Windows machine in any noticeable way between the reboot intervals enforced every 'Patch Tuesday'.
I'm sure you have plenty more bugs with more serious effects to deal with. If not, you can have some of mine!
Rgds,
Martin
My application has to suspend and resume a different process every few *microsec*s.
It works fine only sometimes it feels like it suspends the process for non-uniforms times.
I use the win API: ResumeThread and SuspendThread.
On the other hand, I tried something a little different.
I suspended the thread as usual with SuspendThread but when I resume it, I do like so:
while (ResumeThread(threadHandle) > 0);
and it works faster and it runs the other process in a uniform pace.
Why does it happen? is it possible that sometimes the thread gets suspended twice and then the ResumeThread command executes?
thanks :)
SuspendThread() call does not suspend a thread instantly. It takes several time to save an execution context, so that ResumeThread() might be called when a thread has not suspended yet. That's why while (ResumeThread(threadHandle) > 0); works. To determine the current thread state you can call NtQueryInformationThread(), but only in NT versions of Windows.
If you have a loop in the secondary thread, you can change your synchronization with a Manual Reset Event. The primary thread should call ResetEvent() to suspend a thread, and SetEvent() to resume. The secondary thread every loop should call WaitForSingleObjectEx().
I followed Damon's suggestion, removed suspend / resume from the code and instead used a synchronization object over which my pool thread waits infinitely after completing the work and the same is signaled by my server thread after allocating work to it.
The only time I have to use suspend now is when I create the thread for the first time and after allocating work to it the thread is resumed from my server thread. The thread created is used in a thread pool over and over again to do some work.
It is working like a charm.
Thank you Damon!
Regards,
Ajay
thats the way de loop look's like
for(i=0;i<num;i++) {
while (ResumeThread(threadHandle) > 0);
ResumeThread(threadHandle)
SuspendThread(threadHandle);
}
SuspendThread takes a few milliseconds so the while loop goes on until thread is suspended, after that, again the thread process SuspendThread function is called, a good way to call GetProcessContext to see EIP