《windows 核心编程》学习笔记(二)

发布时间:2014-10-23 23:29:34
来源:分享查询网

这本书的第二部分主要讲述进程与线程,记得当初去面试时经常也会被问到进程与线程的知识。在学习进程与线程之前,或许应该先让我们来看看最原始的东西,大家应该都学过数电吧,现在的计算机最原始的东西只有0和1,电脑上电前,这些0和1储存在物理内存上,启动以后,计算机的心脏cpu开始活动,cpu比这些0和1功能强大一点,可以将它们分到cpu的寄存器中,更可以对这些寄存器中的0和1进程运算,简单的运算有加,一个与或门就ok了,组成算术逻辑单元(arithmetic logic unit,ALU),另外还有专门的浮点运算器。cpu就这样不断地读取数据,运算数据,输出数据,我们就就看到了一台pc运行起来了。 cpu跑的很好啊,那进程是用来干什么的,进程(英文Process,大陆译作进程,台湾译作行程), 是电脑中以执行程式的实体。 进程曾是时分操作系统中的基本运作单位,在面向进程设计的系统(如早期的UNIX,Linux 2.4及更早的版本)中,进程是程序的基本执行实体;在面向线程设计的系统(如当代多数操作系统、Linux 2.6及更新的版本)中,行程本身不是基本执行单位,而是执行者的容器。程式本身只是指令、数据及其组织形式的描述,行程才是程式(那些指令和数据)的真正執行实例。 最近还在网上看到一篇漫画,言简意赅,简单阐释了进程与线程,图不错,http://www.ruanyifeng.com/blog/2013/04/processes_and_threads.html,文章的最后作者做了一个深刻的总结: “操作系统的设计,因此可以归结为三点: (1)以多进程形式,允许多个任务同时运行; (2)以多线程形式,允许单个任务分成不同的部分运行; (3)提供协调机制,一方面防止进程之间和线程之间产生冲突,另一方面允许进程之间和线程之间共享资源。” ————by阮一峰 有没有想动手做一个操作系统的冲动? 给大家看一下ms自己写的入口函数吧: int _stdcall ModuleEntry(void) { int i; STARTUPINFO si; SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS); // // Do runtime startup initializers. // _initterm( __xi_a, __xi_z ); // // do C++ constructors (initializers) specific to this EXE // _initterm( __xc_a, __xc_z ); LPTSTR pszCmdLine = GetCommandLine(); if ( *pszCmdLine == TEXT('\"') ) { /* * Scan, and skip over, subsequent characters until * another double-quote or a null is encountered. */ while ( *++pszCmdLine && (*pszCmdLine != TEXT('\"')) ); /* * If we stopped on a double-quote (usual case), skip * over it. */ if ( *pszCmdLine == TEXT('\"') ) pszCmdLine++; } else { while (*pszCmdLine > TEXT(' ')) pszCmdLine++; } /* * Skip past any white space preceeding the second token. */ while (*pszCmdLine && (*pszCmdLine <= TEXT(' '))) { pszCmdLine++; } si.dwFlags = 0; GetStartupInfo(&si); g_bMirroredOS = IS_MIRRORING_ENABLED(); i = _tWinMain(GetModuleHandle(NULL), NULL, pszCmdLine, si.dwFlags & STARTF_USESHOWWINDOW ? si.wShowWindow : SW_SHOWDEFAULT); ExitProcess(i); return i; // We never comes here. } _tmain() int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { //加载函数: LoadFunc(); //----------------------------------------------------------------------------------------- g_hInstance = hInstance; int retval = TRUE; HKEY hKeyPolicy=NULL; DWORD dwType=0, dwData = 0, dwSize=0; int cx=0, cy=0; //注册窗口消息: g_msgTaskbarCreated = RegisterWindowMessage(TEXT("TaskbarCreated")); //初始化临界区: InitializeCriticalSection(&g_CSTrayThread); //开启互斥: g_hStartupMutex = CreateMutex(NULL, TRUE, cszStartupMutex); if (g_hStartupMutex && GetLastError() == ERROR_ALREADY_EXISTS) { // Give the other instance (the one that owns the startup mutex) 10 // seconds to do its thing WaitForSingleObject(g_hStartupMutex, FINDME_TIMEOUT); } //-------------------------------------------------------------------------------------------------- //加载必要的DLL: HINSTANCE hWinstaDLL = LoadLibrary( TEXT( "winsta.dll" ) ); if( hWinstaDLL != NULL) { gpfnWinStationGetProcessSid = ( pfnWinStationGetProcessSid )GetProcAddress(hWinstaDLL, "WinStationGetProcessSid"); if( gpfnWinStationGetProcessSid == NULL ) { dprintf(TEXT("GetProcAddress for WinStationGetProcessSid failed, Error %d\n") , GetLastError() ); } gpfnWinStationTerminateProcess = ( pfnWinStationTerminateProcess )GetProcAddress(hWinstaDLL, "WinStationTerminateProcess"); if( gpfnWinStationTerminateProcess == NULL ) { dprintf(TEXT("GetProcAddress for WinStationTerminateProcess failed, Error %d\n") , GetLastError() ); } } else { dprintf(TEXT("Cannot Load winsta.dll, Error %d\n"), GetLastError() ); } HINSTANCE hUtilDll = LoadLibrary( TEXT( "utildll.dll" ) ); if( hUtilDll != NULL ) { gpfnCachedGetUserFromSid = ( pfnCachedGetUserFromSid )GetProcAddress(hUtilDll, "CachedGetUserFromSid"); if( gpfnCachedGetUserFromSid == NULL ) { dprintf( TEXT( "GetProcAddress for CachedGetUserFromSid failed, Error %d\n" ) , GetLastError( ) ); } } else { dprintf( TEXT( "Cannot Load utildll.dll, Error %d\n" ) , GetLastError( ) ); } //--------------------------------------------------------------------------------------------------------------- // // Locate and activate a running instance if it exists. // TCHAR szTitle[MAX_PATH]; if (LoadString(hInstance, IDS_APPTITLE, szTitle, ARRAYSIZE(szTitle))) { HWND hwndOld = FindWindow(WC_DIALOG, szTitle); if (hwndOld) { // Send the other copy of ourselves a PWM_ACTIVATE message. If that // succeeds, and it returns PWM_ACTIVATE back as the return code, it's // up and alive and we can exit this instance. DWORD dwPid = 0; GetWindowThreadProcessId(hwndOld, &dwPid); AllowSetForegroundWindow(dwPid); ULONG_PTR dwResult; if (SendMessageTimeout(hwndOld, PWM_ACTIVATE, 0, 0, SMTO_ABORTIFHUNG, FINDME_TIMEOUT, &dwResult)) { if (dwResult == PWM_ACTIVATE) { goto cleanup; } } } } //------------------------------------------------------------------------------------------------------------------ //获取注册表设置: if (RegOpenKeyEx (HKEY_CURRENT_USER, TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"), 0, KEY_READ, &hKeyPolicy) == ERROR_SUCCESS) { dwSize = sizeof(dwData); RegQueryValueEx (hKeyPolicy, TEXT("DisableTaskMgr"), NULL, &dwType, (LPBYTE) &dwData, &dwSize); RegCloseKey (hKeyPolicy); if (dwData) { TCHAR szTitle[25]; TCHAR szMessage[200]; LoadString (hInstance, IDS_TASKMGR, szTitle, ARRAYSIZE(szTitle)); LoadString (hInstance, IDS_TASKMGRDISABLED , szMessage, ARRAYSIZE(szMessage)); MessageBox (NULL, szMessage, szTitle, MB_OK | MB_ICONSTOP); retval = FALSE; goto cleanup; } } //----------------------------------------------------------------------------------------------------------------- //初始化加载: // No running instance found, so we run as normal InitCommonControls(); InitDavesControls(); // Start the worker thread. If it fails, you just don't // get tray icons //创建工作线程: g_hTrayThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)TrayThreadMessageLoop, NULL, 0, &g_idTrayThread); ASSERT(g_hTrayThread); // Init the page table //-------------------------------------------------------------------------------------- //加载属性页: g_pPages[0] = new CTaskPage; if (NULL == g_pPages[0]) { retval = FALSE; goto cleanup; } g_pPages[1] = new CProcPage; if (NULL == g_pPages[1]) { retval = FALSE; goto cleanup; } g_pPages[2] = new CPerfPage; if (NULL == g_pPages[2]) { retval = FALSE; goto cleanup; } // Load whatever resources that we need available globally if (FALSE == LoadGlobalResources()) { retval = FALSE; goto cleanup; } // Initialize the history buffers if (0 == InitPerfInfo()) { retval = FALSE; goto cleanup; } //---------------------------------------------------------------------------- // Create the main window (it's a modeless dialog, to be precise) g_hMainWnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_MAINWND), NULL, MainWindowProc); if (NULL == g_hMainWnd) { retval = FALSE; goto cleanup; } else { fAlreadySetPos = TRUE; cx = g_Options.m_rcWindow.right-g_Options.m_rcWindow.left; cy = g_Options.m_rcWindow.bottom-g_Options.m_rcWindow.top; SetWindowPos(g_hMainWnd, NULL, g_Options.m_rcWindow.left, g_Options.m_rcWindow.top, cx, cy, SWP_NOZORDER); MyShowWindow(g_hMainWnd, nCmdShow); } //---------------------------------------------------------------------- // We're out of the "starting up" phase so release the startup mutex if (g_hStartupMutex) { ReleaseMutex(g_hStartupMutex); CloseHandle(g_hStartupMutex); g_hStartupMutex = NULL; } // If we're the one, true, task manager, we can hang around till the // bitter end in case the user has problems during shutdown SetProcessShutdownParameters(1, SHUTDOWN_NORETRY); MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { // Give the page a crack at the accelerator HWND hwndPage = NULL; if (g_Options.m_iCurrentPage >= 0) { g_pPages[g_Options.m_iCurrentPage]->GetPageWindow(); } BOOL bHandled = FALSE; bHandled = TranslateAccelerator(g_hMainWnd, g_hAccel, &msg); if (FALSE == bHandled) { if (hwndPage) { bHandled = TranslateAccelerator(hwndPage, g_hAccel, &msg); } if (FALSE == bHandled && FALSE == IsDialogMessage(g_hMainWnd, &msg)) { TranslateMessage(&msg); // Translates virtual key codes DispatchMessage(&msg); // Dispatches message to window } } } //------------------------------------------------------------------------------------------------------------------ cleanup: // We're no longer "starting up" if (g_hStartupMutex) { ReleaseMutex(g_hStartupMutex); CloseHandle(g_hStartupMutex); g_hStartupMutex = NULL; } // Yes, I could use virtual destructors, but I could also poke // myself in the eye with a sharp stick. Either way you wouldn't // be able to see what's going on. if (g_pPages[TASK_PAGE]) delete (CTaskPage *) g_pPages[TASK_PAGE]; if (g_pPages[PROC_PAGE]) delete (CProcPage *) g_pPages[PROC_PAGE]; if (g_pPages[PERF_PAGE]) delete (CPerfPage *) g_pPages[PERF_PAGE]; ReleasePerfInfo(); if( hWinstaDLL != NULL ) { FreeLibrary( hWinstaDLL ); } if( hUtilDll != NULL ) { FreeLibrary( hUtilDll ); } return (retval); }

返回顶部
查看电脑版