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
--Initialized/
not
initialized
--program
data
0x0000000 (text)
00
States of A Process
There are the following states in the lifecycle of a
process:
Assign Released
S
Ready ed Runnin Termi
et
g n-ated
Timeo
ut
Create
d Waiting
for
Activated Acquired resource
Resource
Suspe Blocke
n-ded System d
Deployed ?
2.2 Process Controlling
LPSECURITY_ATTRIBUTES lpThreadAttributes,
BOOL bInheritHandles,
DWORD dwCreationFlags,
LPVOID lpEnvironment,
LPCTSTR lpCurrentDirectory,
LPSTARTURINFO lpStartupInfo,
LPPROCESS_INFORMATION
lpProcessInformation
);
CreateProcess( ) – creation of a child process ?
[Version 5.1.2600]
Copyright
#include <stdio.h>
#include <windows.h>
int main() TCHAR cmdline[ ]
{ =TEXT(“cmd”);?
char //
szCommandLine[] = "cmd"; See the notes , _tmain( ), the
…
STARTUPINFO si = {sizeof(si)}; second par.
&si,
PROCESS_INFORMATION
// … pi; &pi);
si.dwFlags = if(bRet)
STARTF_USESHOWWINDOW; {
si.wShowWindow = TRUE; ::CloseHandle(pi.hThread);
::CloseHandle(pi.hProcess);
BOOL bRet = ::CreateProcess( printf(“The New Process ID: %d\n",
NULL, pi.dwProcessId);
szCommandLine, printf(“The Main Thread ID: %d\n",
NULL, pi.dwThreadId);
// …
NULL, }
FALSE,
// Close the handles return 0;
CREATE_NEW_CONSOLE, }
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
typedef struct tagPROCESSENTRY32
process {
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 The
all the Process ID
do processes in
{ the system
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
returns the handle of the currently executing
process (that is,
the caller), and the latter returns the caller’s id.
id is just a number, this number is usually used to
identify
the identity of the process. The process handle is
used as a
10. Terminate the current
and other processes
The process is terminated from the start to
the end of the main function (it is a non
forced termination). At this time, the
system will release the occupied resources,
close the kernel object, etc ;
If a process wants to stop executing of the
current process, calls ExitProcess():
VOID ExitProcess(UNT uExitCode);
In general, C/C++ application programming
does not call it directly, but calls exit() in C
library, and then calls exitprocess() after
some garbage removal work is performed
10. Terminate the current and
other processes
If process a wants to force process B to stop execution, it can
call TerminateProcess():
BOOL TerminateProcess (HANDLE hProcess,
UNIT uExitCode);
(Use HANDLE OpenProcess ( ) first. See the
notes for details)
HANDLE OpenProcess(
DWORD dwDesiredAccess ,
BOOL bInheritHandle,
DWORD dwProcessID
);
2.3 Pipeline for communication
between two processes
Pipe is a process chain composed of standard input and output
streams. The output of one process is directly used as the input
of the next process. Each connection is an anonymous pipe.
The pipe contains a write handle and a read handle. One
process uses a write handle to write data to the pipe, and
another process uses a read handle to read data from the pipe.
The pipeline can be created by calling the CreatePipe() function.
The function prototype is as follows:
BOOL WINAPI CreatePipe(
__out PHANDLE hReadPipe, // read handle
__out PHANDLE hWritePipe,
__in LPSECURITY_ATTRIBUTES lpPipeAttributes,
__in DWORD nSize
);
1.Use pipeline for communication between two
processes
// Main process, Code of Server Side :
#include "stdafx.h"
#include <windows.h>
int _tmain(int argc, _TCHAR* argv[])
{ HANDLE hRead; // Read handle of the pipe
HANDLE hWrite; // Write handle of the pipe
SECURITY_ATTRIBUTES sa; // Set the attributes of the pipe
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;// the pipeline can be inherited by child
processesBOOL bRet = CreatePipe(&hRead, &hWrite, &sa, 0); // Create an
//
anonymous pipeline
if (bRet == TRUE)
printf(" Anonymous pipeline is created successfully!\n");
else
printf(" Failed to create anonymous pipeline, error code:%d\n",
GetLastError());
// Get the current standard output of this process for future recovery
HANDLE hTemp = GetStdHandle(STD_OUTPUT_HANDLE);
// Set standard output to anonymous pipeline
SetStdHandle(STD_OUTPUT_HANDLE, hWrite);
STARTUPINFO si;
GetStartupInfo(&si); // Get the STARTUPINFO structure information of this
process,
// including the handle of the standard device
PROCESS_INFORMATION pi;
// Create the client terminal process client.exe, which will inherit the standard
output // of the parent process, so the standard output of client.exe is to the
hWrite pipeline bRet = CreateProcess(NULL, "Client.exe", NULL, NULL, TRUE,
NULL, NULL, NULL, &si, &pi);
SetStdHandle(STD_OUTPUT_HANDLE, hTemp); // Restore the standard output
of
// this process
if (bRet == TRUE) // Input information
printf(" Child process is created successfully!\n");
else
printf(" Failed to create child process, error code:%d\n", GetLastError());
// Read pipe until pipe is closed
char ReadBuf[200];
DWORD ReadNum;
// Read data from the pipeline circularly
while (ReadFile(hRead, ReadBuf, 200, &ReadNum, NULL)) {
ReadBuf[ReadNum] = '\0';
printf(“ Read % d bytes data from pipeline: [%s]\n", ReadNum,
ReadBuf);
}
if (GetLastError() == ERROR_BROKEN_PIPE) // Output info
printf(" Pipeline is closed by child process \n");
else
printf(" Error in reading data, error code: %d\n",
GetLastError());
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.