0% found this document useful (0 votes)
4 views

Chapter 2 Windows Process Programming

Chapter 2 covers Windows Process Programming, detailing concepts of processes, process control, and inter-process communication. It explains the structure and lifecycle of processes, how to create and manage them using functions like CreateProcess() and ShellExecute(), and methods for inter-process communication using pipes. Additionally, it discusses acquiring system processes and terminating processes, providing code examples for practical understanding.

Uploaded by

SHIMELS KEBEDE
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Chapter 2 Windows Process Programming

Chapter 2 covers Windows Process Programming, detailing concepts of processes, process control, and inter-process communication. It explains the structure and lifecycle of processes, how to create and manage them using functions like CreateProcess() and ShellExecute(), and methods for inter-process communication using pipes. Additionally, it discusses acquiring system processes and terminating processes, providing code examples for practical understanding.

Uploaded by

SHIMELS KEBEDE
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 30

Chapter 2

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

Heap, Increasing to upward


Free space
Interrupted

--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

NULL, // Using the drive and directory of this process


&si, // The position, size and standard handle of the main
// window passing to the process (structure-SI)
&pi // Returns the flag information of the created process,
// such as ID number, handle, etc. (structure-PI)
4.Example of creating a child process
 The program on the next page creates a process to open the command
line executable program “cmd.exe” that comes with windows. After
running, it is a command line based DOS system:

New Process ID: 1388


Main Thread ID: 656

[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

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


parameter by the process-related function.
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 automatically.
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>

using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
for (int i = 0; i< 10; i++) // Send some data to standard output and standard error
{
printf("i = %d; ", i); // Print prompt;
cout << " standard output : " << i << endl; // Print to standard output
cerr << " standard error : " << i << endl; // Print to standard error
}

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.

Submit electronic documents to :


[email protected]

You might also like