Basic use of thread process in windows core programming

Insert picture description here

Source: WeChat Official Account "Programming Learning Base"

Process

在windows系统中,进程就是一个正在运行的程序,他拥有自己的虚拟地址空间,拥有自己的代码,数据和其他系统资源,一个进程也包含了一个或多个运行在此进程中的线程

CreateProcess function

BOOL CreateProcess 
( 
	LPCTSTR lpApplicationName, 	//可执行文件名称
	LPTSTR lpCommandLine, 		//指定了要传递给执行函数的参数
	LPSECURITY_ATTRIBUTES lpProcessAttributes,//NULL
	LPSECURITY_ATTRIBUTES lpThreadAttributes,  //NULL
	BOOL bInheritHandles, 		//指定是否可以被新进程继承
	DWORD dwCreationFlags, 		//进程优先级
	LPVOID lpEnvironment, 		//新进程使用的环境变量
	LPCTSTR lpCurrentDirectory, //新进程当前目录
	LPSTARTUPINFO lpStartupInfo, //主窗口的位置,大小和标准句柄
	LPPROCESS_INFORMATION lpProcessInformation //返回进程的标志信息
); 

Process STARTUPINFO

typedef struct _STARTUPINFO 
{
    
     
	DWORD cb;			//包含STARTUPINFO结构中的字节数,将cb初始化为sizeof(STARTUPINFO) 
    PSTR lpReserved;	//保留。必须初始化为NULL
    PSTR lpDesktop;		//指定桌面名称
    PSTR lpTitle;		//控制台应用程序标题
    DWORD dwX;			//用于设定应用程序窗口相对屏幕左上角位置的x 坐标(以像素为单位)。 
    DWORD dwY;		    //对于GUI processes用CW_USEDEFAULT作为CreateWindow的x、y参数
    DWORD dwXSize;		//用于设定应用程序窗口的宽度(以像素为单位)
    DWORD dwYSize;			 
    DWORD dwXCountChars;//控制台窗口的行数
    DWORD dwYCountChars; 
    DWORD dwFillAttribute;   //用于设定子应用程序的控制台窗口使用的文本和背景颜色 
    DWORD dwFlags;           //请参见下一段和表4-7 的说明 
    WORD wShowWindow;        //窗口的风格
    WORD cbReserved2;        //保留。必须被初始化为0 
    PBYTE lpReserved2;       //保留。必须被初始化为NULL
    HANDLE hStdInput;        //用于设定供控制台输入和输出用的缓存的句柄。
    HANDLE hStdOutput; 
    HANDLE hStdError; 
} STARTUPINFO, *LPSTARTUPINFO;

Get the STARTUPINFO structure of the current process: GetStartupInfo();

Simple to use

#include<Windows.h>
#include<stdio.h>
int main()
{
    
    
	STARTUPINFO si = {
    
     sizeof(si) };
	PROCESS_INFORMATION pi;
	CreateProcess("C:\\Program Files\\Notepad++\\notepad++.exe",//需要创建的进程是谁(路径文件名)
		nullptr,//命令行参数
		nullptr,//是否被子进程所继承
		nullptr,//是否被子线程所继承
		false,//新创建的进程是否从调用线程处继承了句柄
		0,//创建标志
		nullptr,//新进程的环境块
		nullptr,//子进程的工作路径
		&si,
		&pi);
	printf("新的进程Id:%d\n", pi.dwProcessId);
	return 0;
}

The program will open C:\\Program Files\\Notepad++\\notepad++.exethe NotePad program in the C drive path of the computer

#include<Windows.h>
int main()
{
    
    
	STARTUPINFO si = {
    
     sizeof(si) };
	PROCESS_INFORMATION pi;
	char* Command = "notepad";
	CreateProcess(NULL, Command, NULL, NULL, FALSE, NULL, NULL, NULL, &si, &pi);
	return 0;
}

The program runs to create a process, open Notepad, which is opened by parameters

Ways to end the process

  1. The entry function of the main thread of the process returns (equivalent to ending the process you created)
  2. Call TerminateProcess at a thread of the parent process to end a child process
  3. Call ExitProcess somewhere in the current process to end yourself
#include<Windows.h>
#include<stdio.h>
int main()
{
    
    
	STARTUPINFO si = {
    
     sizeof(si) };
	PROCESS_INFORMATION pi;
	CreateProcess("C:\\Program Files\\Notepad++\\notepad++.exe",//需要创建的进程是谁(路径文件名)
		nullptr,//命令行参数
		nullptr,//是否被子进程所继承
		nullptr,//是否被子线程所继承
		false,//新创建的进程是否从调用线程处继承了句柄
		0,//创建标志
		nullptr,//新进程的环境块
		nullptr,//子进程的工作路径
		&si,
		&pi);
	printf("新的进程Id:%d\n", pi.dwProcessId);
	HANDLE hinst = pi.hProcess;	//获取该进程的示例句柄
	Sleep(3000);
	//终止当前进程
	//第一种方法就是手动关掉notepad
	TerminateProcess(hinst, NULL);	
	//ExitProcess(0);
	CloseHandle(hinst);
	return 0;
}

Thread

CreateThread function

HANDLE WINAPI CreateThread(
	  _In_opt_  LPSECURITY_ATTRIBUTES  lpThreadAttributes,   
	  _In_      SIZE_T                 dwStackSize,
	  _In_      LPTHREAD_START_ROUTINE lpStartAddress,
	  _In_opt_  LPVOID                 lpParameter,
	  _In_      DWORD                  dwCreationFlags,
	  _Out_opt_ LPDWORD                lpThreadId
	);

Parameter Description:

  • The first parameter lpThreadAttributesrepresents the security thread kernel object attributes, generally passing NULL indicates the default settings.
  • The second parameter dwStackSizerepresents the thread stack space. Passing in 0 means to use the default size (1MB).
  • The third parameter lpStartAddressrepresents the address of the new thread thread functions performed by multiple threads can use the same function address.
  • The fourth parameter lpParameteris passed to the thread function parameters.
  • The fifth parameter dwCreationFlagsto specify additional flags to control the creation of a thread, the thread is created immediately after 0 means can be scheduled to run after the pause if CREATE_SUSPENDED said thread creation, so that it can not be scheduled until the call ResumeThread ().
  • The sixth parameter lpThreadIdreturns the ID number of the thread, passing NULL indicates that no return to the thread ID number.

return value

Thread creation success returns the handle of the new thread, failure returns NULL

WaitForSingleObject function

DWORD WINAPI WaitForSingleObject(
    _In_ HANDLE hHandle,
    _In_ DWORD dwMilliseconds
    );

The first parameter _In_ HANDLE hHandleis the handle to the object, which can be the following:

The second parameter _In_ DWORD dwMillisecondsis the latency in milliseconds.

The parameter dwMilliseconds has two values ​​with special meaning: 0 and INFINITE.

If it is 0, the function returns immediately;

If it is INFINITE, the thread has been suspended until the object pointed to by hHandle becomes signaled.

#include <stdio.h>
#include <windows.h>

// 线程函数
DWORD WINAPI ThreadProc(LPVOID lpParam)
{
    
    
	for (int i = 0; i < 10; i++)
	{
    
    
		printf("I am Thread :%d\trun\n", GetCurrentThreadId());
		
	}
	return 0;
}

int  main(int argc, char* argv[])
{
    
    
	HANDLE hThread;
	DWORD dwThreadId;

	// 创建一个线程
	hThread = CreateThread(
		NULL,		// 默认安全属性
		NULL,		// 默认堆栈大小
		ThreadProc,	// 线程入口地址(执行线程的函数)
		NULL,		// 传给函数的参数
		0,		// 指定线程立即运行
		&dwThreadId);	// 返回线程的ID号
	printf(" Now another thread has been created. ID = %d \n", dwThreadId);

	// 等待新线程运行结束
	WaitForSingleObject(hThread, INFINITE);
	CloseHandle(hThread);
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_44519484/article/details/108754540