C ++ windows Kernel programming notes day13 process, thread and semaphore, kernel day13

Source: Internet
Author: User

C ++ windows Kernel programming notes day13 process, thread and semaphore, kernel day13
A Windows Process is a container that contains the code, Data, resources, and other information required for program execution,
Features of windows processes:
Each process has its own ID.
Each process has its own address space, and processes cannot access the address space of the other side.
Each process has its own security attributes.
Each process contains at least one thread.
Obtain and release Environment Information
GetEnvironmentStrings
FreeEnvironmentStrings
Obtain or set the environment variables of the program
GetEnvironmentVariable
SetEnvironmentVariable
Example:
Char * env = (char *) GetEnvironmentStrings ();
Char * env2 = env;
While (env2 [0])
{
Printf ("% s \ n", env2 );
Env2 = env2 + strlen (env2) + 1;
}
FreeEnvironmentStrings (env );
SetEnvironmentVariable ("abc", "100 ");
Char buf [10] = {0 };
GetEnvironmentVariable ("abc", buf, 256 );
Printf ("% s \ n", buf );


Process Information
1. process ID
DWORD pid = GetCurrentProcessId ();
2. Process Handle
HANDLE hpro = GetCurrentProcess ();
3. Start the process
BOOL CreateProcess (
Lptstr lpApplicationName, // Application name
LPTSTR lpCommandLine, // command line parameters
LPSECURITY_ATTRIBUTES lpProcessAttributes, // SD
LPSECURITY_ATTRIBUTES lpThreadAttributes, // SD
BOOL bInheritHandles, // whether the quilt process can be used
DWORD dwCreationFlags, // Creation Method
LPVOID lpEnvironment, // Environment Information
Maid directory, // Current Directory
LPSTARTUPINFO lpStartupInfo, // returned: Start Information
LPPROCESS_INFORMATION lpProcessInformation // returned Process Information
);
Example:
STARTUPINFO stinfo = {0 };
PROCESS_INFORMATION pi = {0 };
CreateProcess ("C:/Windows/System32/calc.exe", 0, NULL, NULL, TRUE, 0, NULL, NULL,
& Stinfo, & pi );
WaitForSingleObject (pi. hProcess, INFINITE); // wait for the signal (generally there is a signal when the process ends)
Printf ("Processid = % d, handle = % d \ n", pi. dwProcessId, pi. hProcess );
Exit this process
VOID ExitProcess (UINT uExitCode // exit code
);
Exit any process
BOOL TerminateProcess (HANDLE hProcess, // handle to the process
UINT uExitCode // exit code for the process
);


Get Process Handle By process ID
HANDLE OpenProcess (
DWORD dwDesiredAccess, // access flag
BOOL bInheritHandle, // handle inheritance option
DWORD dwProcessId // process identifier
);
Example of getting and disabling a process (process ID is 32 ):
HANDLE calc = OpenProcess (PROCESS_ALL_ACCESS, FALSE, 32 );
TerminateProcess (calc,-1 );
Waiting between processes, waiting for the arrival of process/thread Signals
(Generally there is a signal when the process ends)
DWORD WaitForSingleObject (
HANDLE hHandle, // handle to object
DWORD dwMilliseconds // time-out interval
);

Windows threads are executable code instances. The System Schedules programs in units of threads.
Windows Thread features:
All threads have IDs.
The thread has its own security attributes.
Memory stack for threads
Each thread has its own register information.
Process Multitasking: each process uses a private address space.
Multi-task thread: multiple threads in a process use the same address space.
Thread processing functions:
Dword winapi ThreadProc (
LPVOID lpParameter // thread data
);
HANDLE CreateThread (
LPSECURITY_ATTRIBUTES lpThreadAttributes, // SD
SIZE_T dwStackSize, // thread stack size (1 MB by default)
LPTHREAD_START_ROUTINE lpStartAddress, // thread processing function
LPVOID lpParameter, // parameter passed to the thread processing function
DWORD dwCreationFlags, // creation option
LPDWORD lpThreadId // return value: thread ID
);
DwCreationFlags:
0-execute immediately after creation
Create_suincluded-suspended after creation, not executed immediately


// End the thread, Which is used the same as the End Process
TerminateThread (...)
ExitThread (...);
CloseHandle () // closes the thread handle, not the end thread
WaitForSingleObject () can be used to wait for the thread to end
Suspend thread
DWORD SuspendThread (HANDLE hThread // handle to thread );
Recovery thread
DWORD ResumeThread (HANDLE hThread // handle to thread );
Example:
Dword callback TestProc1 (LPVOID param)
{
Char * txt = (char *) param;
While (1)
{
Printf ("% s \ n", txt );
Sleep (1000 );
}
}
Dword callback TestProc2 (LPVOID param)
{
Char * txt = (char *) param;
While (1)
{
Printf ("% s \ n", txt );
Sleep (1000 );
}
}
Void Thread ()
{
DWORD tid = 0;
Char * txt = "*************************";
HANDLE hthread1 = CreateThread (NULL, 0, TestProc1, txt,
0, & tid );
Char * txt2 = "------------";
HANDLE hthread2 = CreateThread (NULL, 0, TestProc2, txt2,
Create_suincluded, & tid );
Getchar ();
SuspendThread (hthread1); // suspend
ResumeThread (hthread2); // restore
}
Obtain the thread ID and handle, similar to the process operation:
GetCurrentThreadId
GetCurrentThread

OpenThread



Sample Process Code:

// WinEnv. cpp: Defines the entry point for the console application. // # include "stdafx. h "# include <STDIO. h> # include <WINDOWS. h> void winProc () {char * env = (char *) GetEnvironmentStrings (); char * env2 = env; while (env2 [0]) {printf ("% s \ n", env2); env2 = env2 + strlen (env2) + 1;} FreeEnvironmentStrings (env); SetEnvironmentVariable ("abc ", "100"); char buf [10] = {0}; GetEnvironmentVariable ("abc", buf, 256); printf ("% s \ n", buf ); DWORD pid = GetCurrentProcessId (); HANDLE hpro = GetCurrentProcess ();} void CreateProc () {STARTUPINFO stinfo = {0}; PROCESS_INFORMATION pi = {0}; CreateProcess ("C: /Windows/System32/calc.exe ", 0, NULL, NULL, TRUE, 0, NULL, NULL, & stinfo, & pi); WaitForSingleObject (pi. hProcess, INFINITE); // wait for the signal (usually only after the process ends) printf ("Processid = % d, handle = % d \ n", pi. dwProcessId, pi. hProcess);} void KillProc () {HANDLE calc = OpenProcess (PROCESS_ALL_ACCESS, FALSE, 32); TerminateProcess (calc,-1);} int main (int argc, char * argv []) {// winProc (); CreateProc (); // KillProc (); return 0 ;}


Example of how to use threads and semaphores (semaphores are a thread synchronization technology ):

// WinThread. cpp: Defines the entry point for the console application. // # include "stdafx. h "# include <stdio. h> # include <windows. h> char g_txt [256]; char g_txt2 [256]; CRITICAL_SECTION cs = {0}; HANDLE g_hSem = 0; dword callback PrintProc (LPVOID param) {char buf [10] = {0}; while (1) {WaitForSingleObject (g_hSem, INFINITE); // ZeroMemory (buf, sizeof (buf) is executed only when there is a signal )); getEnvironmentVariable ("exit", buf, sizeof (buf); if (strcmp (buf ," 1 ") = 0) break; printf ("************************** \ n");} return 0 ;} /* dword callback CtrlProc (LPVOID param) {int I = 0; while (1) {SetEvent (g_hevent); // send a signal Sleep (1000); I ++; if (I = 1000) break;} return 0;} */void Thread () {DWORD tid = 0; char * txt = "************************"; HANDLE hthread1 = CreateThread (NULL, 0, PrintProc, txt, 0, & tid);/* // char * txt2 = "-------------"; // HANDLE hthread2 = CreateThread (NULL, 0, CtrlProc, txt2, // 0, & tid); // HANDLE ht [2] = {0}; // ht [0] = hthread1; // ht [1] = hthread2; // WaitForMultipleObjects (2, ht, TRUE, INFINITE); */SetEnvironmentVariable ("exit", "0"); while (1) {char c = getchar (); if (c = '\ 0' | c =' \ n') continue; int count = c-'0 '; printf ("count1 = % d \ n", count); if (count> = 0 & count <= 9) {printf ("count2 = % d \ n ", count); ReleaseSemaphore (g_hSem, count, NULL); // reset to 5 times} else if (c = 'E' | c = 'E ') {SetEnvironmentVariable ("exit ", "1"); ReleaseSemaphore (g_hSem, 1, NULL); // reset to 5 break;} WaitForSingleObject (hthread1, INFINITE); printf ("wait over! \ N "); CloseHandle (hthread1); // CloseHandle (hthread2);} int main (int argc, char * argv []) {g_hSem = CreateSemaphore (NULL, 3,10, "s1"); Thread (); CloseHandle (g_hSem); return 0 ;}






What are the differences between process semaphores and thread semaphores in linux?

Semaphores are used to communicate with processes based on famous semaphores, while threads communicate with each other based on unknown signals. Because thread linux does not implement inter-process communication, therefore, the second parameter in sem_init must be 0, and the synchronization between multiple threads can also pass the unknown signal through the famous semaphores, but generally the thread synchronization is an unknown semaphores, the unknown semaphores are easy to use, and sem_t is stored in the process space. The famous semaphores must be managed by the Linux kernel, and are stored by the kernel structure struct ipc_ids. They are continuously stored with the kernel. if the system is disabled, the semaphores are deleted, of course, deletion can also be displayed and deleted through system calls,
Message Queue, semaphore, and Memory sharing are the same principles ., However, semaphores are classified into famous and unknown.
 
Thread problems in Windows kernel (driver) Programming

The PsCreateSystemThread function can be used, which is similar to ring3. ring0 programming should pay more attention to thread synchronization. Otherwise, it is easy to use BSOD (blue screen crashes)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.