Chapter 2 Windows Process Programming
Chapter 2 Windows Process Programming
Windows Process
Programming
Outlines
2.1 Concepts of Process
2.2 Process Controlling
2.3 Inter-process Communication
Concepts of Process;
Create Process: The use of CreateProcess()
function;
Methods of System process acquisition and
termination;
Inter-process communication with pipe.
2.1 Concepts of Process
A process is an instance of a running program.
Each running project corresponds to a process.
Each process contains at least one thread (main
thread).
It starts execution from the main() function until the
return statement is executed.
When the main thread terminates , the process is
unloaded from memory.
A process consists of the following 5 parts:
A mirroring of executable code associated with the
program;
Memory space (usually some areas in virtual memory),
which holds specific data of executable codes and-
2.1 Concepts of Process
process, stacks for recording active routines and
other events, and heaps for saving intermediate
calculation results generated in real time );
Operating system descriptors (such as file handles) of
the resources allocated to the process and other data
resources;
Security attributes: process owner and permissions;
The state of the processor: the contents of registers,
physical memory addresses, etc.
2.1 Concepts of Process
Virtual memory
addresses
Kernel
(hexadecimal) Mapped to the virtual memory of the process. Application
0xC00000000
program cannot access
Argv. Environ.
Stack, Increasing downward
Top of the
stack
Free space
non-allocated memory
--Initialized/not
initialized data
--program (text)
0x000000000
States of A Process
There are the following states in the lifecycle of a process:
Assigned Released
Set
Ready Termin-
Running
ated
Timeout
Created
Waiting for
resource
Activated Acquired
Resource
Suspen-
Blocked
ded System
Deployed ?
2.2 Process Controlling
When a new process is created, the system specifies
a structure variable called STARTUPINFO for the new
process;
This structure contains some display information
passed from the parent process to the child process;
For GUI applications, these information will
determine the display of main window of the main
thread in the new process;
If a new console window is created, this information
will determine the console window;
The structure is defined as follows :
1. Structure Of STARTUPINFO
typedef struct{
DWORD cb; // Length of the structure
LPSTR lpReserved; // Reserved parameter
LPSTR lpDesktop; // Name of desk
LPSTR lpTitle; // Name of console window
DWORD dwX; // Coordinates defined position and size
DWORD dwY;
DWORD dwXSize;
DWORD dwYSize;
DWORD dwXCountChars; // Specify the number of lines in the console window
DWORD dwYCountChars;
DWORD dwFillAttributes; // Specify background color on the console window
DWORD dwFlags; // Flags, which member values in the structure are valid
WORD wShowWindow; // Display modes of Windows
WORD cbReserved2;
LPBYTE lpReserved2;
HANDLE hStdInput; // Used by console, several standard handles
HANDLE hStdOutput;
HANDLE hStdError;
} STARTUPINFO, *LPSTARTUPINFO;// Names available at structure declaration
2.PROCESS_INFORMATION
The new process identity information can be obtained
through the PROCESS_INFORMATION structure;
typedef struct{
HANDLE hProcess; // Kernel handle of the new process
HANDLE hThread; // kernel handle of the main thread
DWORD dwProcessId; // ID of the process
DWORD dwThreadId; // Main thread ID
}PROCESS_INFORMATION,
*LPPROCESS_INFORMATION;
3. Child Process Creation
CreateProcess() , its prototype :
BOOL CreateProcess(
LPCTSTR lpApplicationName,
LPTSTR lpCommandLine,
LPSECURITY_ATTRIBUTES lpProcessAttributes,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
BOOL bInheritHandles,
DWORD dwCreationFlags,
LPVOID lpEnvironment,
LPCTSTR lpCurrentDirectory,
LPSTARTURINFO lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation
);
CreateProcess( ) – creation of a child process ?
The detail info. Can be found in msdn
3. Child Process Creation
The variables used to create the process in the example :
CreateProcess (
NULL, // File name ( no )
szCommandLine, // CommandLine par. passed to module
NULL, // Attr. of process ( not inherited )
NULL, // Attr. of thread ( not inherited )
FALSE, // Handles in the process can not be called by
// inherited processes
CREATE_NEW_CONSOLE, // New process is with console window
NULL, // Using the environment variables of this process
[Version 5.1.2600]
Copyright
#include <stdio.h>
#include <windows.h>
int main() TCHAR cmdline[ ] =TEXT(“cmd”);?
{ See the notes , _tmain( ), the second
char szCommandLine[]
// … = "cmd"; par.
STARTUPINFO si = {sizeof(si)}; &si,
PROCESS_INFORMATION
// … pi; &pi);
si.dwFlags = STARTF_USESHOWWINDOW; if(bRet)
si.wShowWindow = TRUE; {
::CloseHandle(pi.hThread);
BOOL bRet = ::CreateProcess( ::CloseHandle(pi.hProcess);
NULL, printf(“The New Process ID: %d\n", pi.dwProcessId);
szCommandLine, printf(“The Main Thread ID: %d\n", pi.dwThreadId)
NULL, }
NULL,
// … return 0;
FALSE, }
CREATE_NEW_CONSOLE,
// Close the handles
NULL,
NULL,
The New Process ID:
The Main Thread ID:
5. ShellExecute () , another function
to create child process
HINSTANCE ShellExecute(
HWND hwnd, // Specify the window handle to display the
user
// interface and error messages
LPCTSTR lpOperation, // Operation on the specified file(next ppt)
LPCTSTR lpFile, // File or Object to be operated
LPCTSTR lpParameters, // Parameters passed to the application
LPCTSTR lpDirectory, // Working directory to perform the operation
INT nShowCmd // Display modes,SW_HIDE, hide the window
// SW_MAXIMIZE, maximize the window ,
// SW_MINIMIZE, minimize the window, SW_SHOW,
// default position and size (set by program)
);
6.lpOperation Parameter Values
Table 2-1 lpOperation parameter values and description
value Description
edit Open a document file for editing.
If the parameter lpFile does not
specify a document file, the
operation fails.
explore Open the resource manager to view
the directory where the specified
file is located
find Start searching from the directory
specified by the parameter
lpDirectory
open Open a specified object
print Print the specified object. If the
parameter lpFile does not specify a
document file, the operation fails
NULL Perform the default operation,
usually perform the open operation
7. Use ShellExecute ()
Call ShellExecute () function to access google website,
the code is as follows :
#include "stdafx.h"
#include "windows.h”
int main(int argc, char* argv[])
{
ShellExecute(NULL, "open", "http://www.google.com",
" ", " ", SW_SHOW);
return 0;
}
8. Acquisition of system processes
Use the ToolHelp function to get the current
running process of the system:
Use CreateToolHelp32Snapshot() to take a snapshot of
the current system execution process;
Use Process32First () and Process32Next () to traverse
the list of records in the snapshot;
CreateToolHelp32Snapshot () can also get the list of
heap, modules and threads used by the process, stack
and other objects;
Use the PROCESSENTRY32 structure to get related
attributes.
PROCESSENTRY32--Structure
Definition Used to obtain the related
Information of a process
typedef struct tagPROCESSENTRY32 {
DWORD dwSize;
DWORD cntUsage; // Number of processes referenced
DWORD th32ProcessID;
DWORD th32DefaultHeapID;
DWORD th32ModuleID;
DWORD cntThreads;
DWORD th32ParentProcessID;
LONG pcPriClassBase; // Process base priority
DWORD dwFlags; // System Reserved
CHAR szExeFile[MAX_PATH]; // File Name
}PROCESSENTRY32, *PPROCESSENTRY32;
Acquisition Method of System
Process
CreateToolHelp32Snapshot() :
HANDLE WINAPI CreateToolhelp32Snapshot(
DWORD dwFlags, // The object to be returned in the snapshot
DWORD the32ProcessID // The process ID to get
);
Values of dwFlags :
TH32CS_SNAPHEAPLIST // Specify the heap of Proc.
TH32CS_SNAPMODULE // Specify the module of …
TH32CS_SNAPPROCESS // All the processes in the System
TH32CS_SNAPTHREAD // All the threads in the system
Program and its Execution results
Objects to be
returned in the
snapshot - in this
case, enumerates
all the processes
in the system The Process ID
do
{
printf("\n PROCESS NAME: %s", pe32.szExeFile );
printf( "\n Process ID = 0x%08X", pe32.th32ProcessID
Call Failed );
printf( "\n Thread count = %d", pe32.cntThreads );
printf( "\n Traverse
Parentprocesses
process ID = 0x%08X\n\n", pe32.th32ParentProcessID );
} while( Process32Next( hProcessSnap, &pe32 ) );
Process Name:
Process ID:
Close handles
9. Other Functions
HANDLE GetCurrentProcess(VOID);
DWORD GetCurrentProcessId(VOID);
DWORD GetPriorityClass(HANDLE hProcess);
BOOL SetPriorityClass(HANDLE hProcess,
DWORD dwPriorityClass);
BOOL EnumProcesses(…) // Enumerate processes -Win Vista
// or higher version
GetCurentProcess() and GetCurrentProcessId(), The former
return 0;
}
Code of Client :
#include "stdafx.h"
#include <windows.h>
#include <iostream>
return 0;
}
2. 运行结果
Assignment
1. Analyze the different access modes under Windows multitasking,
and explain how the object handle works in Windows multitasking.
2. Design program, use two different functions of process creation to
create child processes, compare the parameter usage and results.
Use the processentry32 structure to list the relevant information of
your new process one by one, and terminate one of the processes in
the program.
3 *. Analyze and compare the characteristics of UNIX system and
Windows system in creating and managing process related functions.