banner.gif adie's blog
主页 博客 胭脂泪,相留醉,几时重,自是人生长恨水长东
统计
日志总数: 127
评论总数: 123
日志分类
日志归档
最近日志
最近评论
订阅
rss2.gif

atom.gif

google_rss
yc.gif 【技术资料】 阅读 37800 次

强制切换一个线程来执行指定的函数

2013-08-05 12:33:20
  1. #include <stdio.h>    
  2. #define _WIN32_WINNT 0x0501    
  3. #include <windows.h>    
  4.   
  5. volatile long th1_start = 0;    
  6. volatile long th1_continue = 0;    
  7. volatile long th2_finished = 0;    
  8.   
  9. DWORD WINAPI thread_fun1(LPVOID arg)    
  10. {    
  11.     InterlockedIncrement(&th1_start);    
  12.   
  13.     while(!th1_continue)    
  14.     {    
  15.         Sleep(1);    
  16.     }    
  17.   
  18.     printf("fun 1: Hello!\n");    
  19.     printf("fun 1: World!\n");    
  20.   
  21.     return 0;    
  22. }    
  23.   
  24. void __declspec(naked) fun2()    
  25. {  
  26.     __asm {   
  27.         pushad   
  28.     }  
  29.   
  30.     printf("fun 2: Hello!\n");    
  31.     printf("fun 2: China!\n");    
  32.   
  33.     InterlockedIncrement(&th2_finished);    
  34.   
  35.     __asm {  
  36.         popad;  
  37.         ret;  
  38.     }  
  39. }    
  40.   
  41. int main()    
  42. {    
  43.     HANDLE hThread = CreateThread(NULL, 0, thread_fun1, 0, 0, 0);    
  44.   
  45.     while(!th1_start)    
  46.         Sleep(1);    
  47.   
  48.     SuspendThread(hThread);    
  49.     CONTEXT ctx;    
  50.     ctx.ContextFlags = CONTEXT_FULL;    
  51.     GetThreadContext(hThread, &ctx);    
  52.   
  53.     ctx.Esp -= 4;  
  54.     *(DWORD*)(DWORD_PTR)ctx.Esp = ctx.Eip;  
  55.     ctx.Eip = (DWORD)(DWORD_PTR)fun2;   
  56.   
  57.     SetThreadContext(hThread, &ctx);    
  58.     FlushInstructionCache(hThread, fun2, 5);  
  59.     ResumeThread(hThread);    
  60.   
  61.     while(!th2_finished)    
  62.     {    
  63.         Sleep(1);    
  64.     }    
  65.   
  66.     InterlockedIncrement(&th1_continue);      
  67.     WaitForSingleObject(hThread, INFINITE);    
  68.     system("pause");    
  69.     return 0;    
  70. }

 

上面的代码实现了让本来在执行 thread_fun1 的线程强制切换来执行 fun2 中的代码. 并在 fun2 执行完后返回到原来的位置.

▲评论

X 正在回复:
姓 名: 留下更多信息
性 别:
邮 件:
主 页:
Q Q:
来 自:
职 业:
评 论:
验 证:


Valid HTML 4.01 Strict Valid CSS!
Copyleft.A!die Software Studio.ADSS
Power by webmaster@adintr.com