1 JMH Associates © 2004, All rights reserved Chapter 6 Process Management.
-
date post
19-Dec-2015 -
Category
Documents
-
view
217 -
download
3
Transcript of 1 JMH Associates © 2004, All rights reserved Chapter 6 Process Management.
2JMH Associates © 2004, All rights reserved
OBJECTIVESOBJECTIVESOBJECTIVESOBJECTIVES
Upon completing this chapter, you will be able to: Describe Windows processes Create and manage independent processes Describe and use the general purpose Windows object
synchronization functions to synchronize processes Be prepared to learn interprocess communication and
thread management
3JMH Associates © 2004, All rights reserved
TOPICSTOPICSTOPICSTOPICS
Topic I Windows Processes and Threads
Topic II Process Management
Topic III Object Sharing and Handle Inheritance
Topic IV Process Termination and Synchronization
Topic V Process Environments and Security
Lab 6-A
Lab 6-B
4JMH Associates © 2004, All rights reserved
TOPIC ITOPIC ITOPIC ITOPIC I
Windows Processes and Threads
5JMH Associates © 2004, All rights reserved
OVERVIEWOVERVIEWOVERVIEWOVERVIEW
A Windows process contains its own independent virtual address space with both code and data
Each process contains one or more independently executed threads
The Windows thread is the basic executable unit A process can
Create new threads within the processes Create new, independent processes Manage communication and synchronization between these
objects This chapter is limited to a single thread within a process
6JMH Associates © 2004, All rights reserved
Windows PROCESSES HAVEWindows PROCESSES HAVEWindows PROCESSES HAVEWindows PROCESSES HAVE
One or more threads Virtual address space which is distinct from other
processes’ address spaces Except for shared memory-mapped files
One or more code segments One or more data segments containing global variables Environment strings with environment variable information The process heap Resources such as open handles and other heaps
7JMH Associates © 2004, All rights reserved
THREADSTHREADSTHREADSTHREADS
Share the code, global variables, environment strings and resources in a process
Are independently scheduled Have a stack for procedure calls, interrupts, etc. Have Thread Local Storage (TLS)—pointers giving each
thread the ability to allocate storage to create its own unique data environment
Have an argument (on the stack) from the creating thread Can also be unique for each thread
Have a context structure, maintained by the kernel, with machine register values
8JMH Associates © 2004, All rights reserved
A PROCESS AND ITS THREADSA PROCESS AND ITS THREADSA PROCESS AND ITS THREADSA PROCESS AND ITS THREADSProcess
Code
Global Variables
Process Heap
Process ResourcesOpen Files, Heaps,
· · ·
Environment Block
· · ·
Thread 1
TLS
Stack
Thread N
TLS
Stack
9JMH Associates © 2004, All rights reserved
FILE SEARCHING USING MULTIPLE FILE SEARCHING USING MULTIPLE PROCESSESPROCESSESFILE SEARCHING USING MULTIPLE FILE SEARCHING USING MULTIPLE PROCESSESPROCESSES
Parent Process
ExitProcess
grep pattern argv [3]
argv [1], argv [2], ..., argv [N+1]
for (i = 1; i <= N; i++) { StartUp.hStdOut =
CreateFile (Temp [i]) CreateProcess (grep pattern
argv [i + 1])}WaitForMultipleObjects;
· · ·
/* Display search results */
for (i = 1; i <= N; i++) { CreateProcess (cat Temp [i]) WaitForSingleObject;}ExitProcess
grep pattern argv [N+1]
ExitProcess
grep pattern argv [2]
ExitProcess
···
All SearchesComplete
10JMH Associates © 2004, All rights reserved
TOPIC IITOPIC IITOPIC IITOPIC II
Process Management and Handle Inheritance
11JMH Associates © 2004, All rights reserved
PROCESS CREATION (1 of 8)PROCESS CREATION (1 of 8)PROCESS CREATION (1 of 8)PROCESS CREATION (1 of 8)
BOOL CreateProcess (LPCTSTR lpImageName,LPTSTR lpCommandLine,LPSECURITY_ATTRIBUTES lpsaProcess,LPSECURITY_ATTRIBUTES lpsaThread,BOOL bInheritHandles, DWORD dwCreate,LPVOID lpvEnvironment, LPCTSTR lpCurDir,LPSTARTUPINFO lpsiStartInfo,LPPROCESS_INFORMATION lppiProcInfo)
Return: TRUE only if the process and thread are successfully created
12JMH Associates © 2004, All rights reserved
PROCESS CREATION (2 of 8)PROCESS CREATION (2 of 8)PROCESS CREATION (2 of 8)PROCESS CREATION (2 of 8)
Parameters
lpImageName — Specifies the executable program
lpCommandLine — Specifies the command line arguments
lpsaProcess — Points to the process security attribute structure
lpsaThread — Points to the thread security attribute structure
(NULL implies default security)
13JMH Associates © 2004, All rights reserved
PROCESS CREATION (3 of 8)PROCESS CREATION (3 of 8)PROCESS CREATION (3 of 8)PROCESS CREATION (3 of 8)
bInheritHandles — This is a “master switch” to indicate that the new process can inherit handles from the parent
Individual handles must still be specified as inheritable A typical use is to redirect standard I/O — there are
numerous examples in the lab exercises
14JMH Associates © 2004, All rights reserved
PROCESS CREATION (4 of 8)PROCESS CREATION (4 of 8)PROCESS CREATION (4 of 8)PROCESS CREATION (4 of 8)
dwCreate — Combines flags, including: CREATE_SUSPENDED — The primary thread is in a
suspended state and will only run when ResumeThread is called
DETACHED_PROCESS — Creates a process without a console
CREATE_NEW_CONSOLE — Gives the new process a console (These two are mutually exclusive. If neither is set, the
process inherits the parent’s console.) CREATE_NEW_PROCESS_GROUP — Specifies that the new
process is the root of a new process group
15JMH Associates © 2004, All rights reserved
PROCESS CREATION (5 of 8)PROCESS CREATION (5 of 8)PROCESS CREATION (5 of 8)PROCESS CREATION (5 of 8)
lpvEnvironment — Points to an environment block for the new process. If NULL, the parent’s environment is used. Contains name/value strings, such as search path.
lpCurDir — Drive and directory for the new process If NULL, parent’s is used)
lpsiStartInfo — Main window appearance for the new process
lppiProcInfo — Structure to contain the returned process and thread handles and identification
16JMH Associates © 2004, All rights reserved
PROCESS CREATION (6 of 8)PROCESS CREATION (6 of 8)PROCESS CREATION (6 of 8)PROCESS CREATION (6 of 8)
typedef struct _PROCESS_INFORMATION {HANDLE hProcess;HANDLE hThread;DWORD dwProcessId;DWORD dwThreadId;} PROCESS_INFORMATION;
Processes and threads need both handles and IDs ID is unique to the object for its lifetime in all processes There may be several handles for a given process Handles are used with many general-purpose functions
17JMH Associates © 2004, All rights reserved
PROCESS CREATION (7 of 8)PROCESS CREATION (7 of 8)PROCESS CREATION (7 of 8)PROCESS CREATION (7 of 8)
typedef struct _STARTUPINFO {/* Lots of information controlling the window */
DWORD dwFlags;HANDLE hStdInput;HANDLE hStdOutput;HANDLE hStdError;
} STARTUPINFO;
18JMH Associates © 2004, All rights reserved
PROCESS CREATION (8 of 8)PROCESS CREATION (8 of 8)PROCESS CREATION (8 of 8)PROCESS CREATION (8 of 8)
Setting these handles before creating the process is a common way to redirect the new process’ standard I/O
Set dwFlags to STARTF_USESTDHANDLES to enable redirection
Use GetStartupInfo (&StartupInfo) to fill in the structure from the parent’s values
19JMH Associates © 2004, All rights reserved
EXECUTABLE IMAGE ANDEXECUTABLE IMAGE ANDCOMMAND LINE (1 of 3)COMMAND LINE (1 of 3)
EXECUTABLE IMAGE ANDEXECUTABLE IMAGE ANDCOMMAND LINE (1 of 3)COMMAND LINE (1 of 3)
lpImageName and lpCommandLine combine to form the executable image name. The rules for determining the command line are:
lpImageName, if not NULL, is the name of the executable Otherwise, executable is the first token in lpCommandLine
A process written in C can obtain command line entries with argc/argv
There is a GetCommandLine function
20JMH Associates © 2004, All rights reserved
EXECUTABLE IMAGE ANDEXECUTABLE IMAGE ANDCOMMAND LINE (2 of 3)COMMAND LINE (2 of 3)
EXECUTABLE IMAGE ANDEXECUTABLE IMAGE ANDCOMMAND LINE (2 of 3)COMMAND LINE (2 of 3)
Rules for lpImageName:
If lpImageName is not NULL, it specifies the executable module. Use full path name, or use a partial name and the current drive and directory will be used. You must include the file extension.
If lpImageName is NULL, the first white-space delimited token in lpCommandLine is the program name. If no extension is specified, .EXE is assumed.
21JMH Associates © 2004, All rights reserved
EXECUTABLE IMAGE ANDEXECUTABLE IMAGE ANDCOMMAND LINE (3 of 3)COMMAND LINE (3 of 3)
EXECUTABLE IMAGE ANDEXECUTABLE IMAGE ANDCOMMAND LINE (3 of 3)COMMAND LINE (3 of 3)
If the name does not contain a full directory path, the search sequence is:
The directory of the current process’ image The current directory The Windows system directory, which you can retrieve with GetSystemDirectory
The Windows directory, which you can retrieve with GetWindowsDirectory
The directories as specified in the environment variable PATH
22JMH Associates © 2004, All rights reserved
TOPIC IIITOPIC IIITOPIC IIITOPIC III
Object Sharing and Handle Inheritance
23JMH Associates © 2004, All rights reserved
INHERITABLE HANDLES (1 of 2)INHERITABLE HANDLES (1 of 2)INHERITABLE HANDLES (1 of 2)INHERITABLE HANDLES (1 of 2)
typedef struct SECURITY_ATTRIBUTES {DWORD nLength;LPVOID lpSecurityDescriptor;BOOL bInheritHandle;
} SECURITY_ATTRIBUTES;
24JMH Associates © 2004, All rights reserved
INHERITABLE HANDLES (2 of 2)INHERITABLE HANDLES (2 of 2)INHERITABLE HANDLES (2 of 2)INHERITABLE HANDLES (2 of 2)
The bInheritHandle flag determines whether the child processes can inherit this specific handle
By default, a handle is not inheritable bInheritHandle should be set to TRUE Parent communicates inheritable handle values to child
with IPC or by assigning an handle to standard I/O Typically in the STARTUPINFO structure
25JMH Associates © 2004, All rights reserved
DUPLICATING HANDLES (1 of 3)DUPLICATING HANDLES (1 of 3)DUPLICATING HANDLES (1 of 3)DUPLICATING HANDLES (1 of 3)
BOOL DuplicateHandle (HANDLE hSourceProcess,HANDLE hSource, HANDLE hTargetProcess,LPHANDLE lphTarget, DWORD dwAccess,BOOL fInherit, DWORD dwOptions)
Creates a copy of the handle hSource that points to lphTarget
hSourceProcess contains hSource hSource must have PROCESS_DUP_HANDLE access hTargetProcess receives the duplicate handle
26JMH Associates © 2004, All rights reserved
DUPLICATING HANDLES (2 of 3)DUPLICATING HANDLES (2 of 3)DUPLICATING HANDLES (2 of 3)DUPLICATING HANDLES (2 of 3)
dwOptions is any combination of two flags: DUPLICATE_CLOSE_SOURCE causes the source handle to be
closed, which will be convenient for our intended application
DUPLICATE_SAME_ACCESS will cause dwAccess to be ignored
dwAccess, if not overridden by DUPLICATE_SAME_ACCESS in dwOptions, has many possible values (see the reference)
27JMH Associates © 2004, All rights reserved
DUPLICATING HANDLES (3 of 3)DUPLICATING HANDLES (3 of 3)DUPLICATING HANDLES (3 of 3)DUPLICATING HANDLES (3 of 3)
DuplicateHandle can be used for any handle type Uses include assigning a duplicated handle to standard
input or output for use by a new process The new handle can have different access than the original
28JMH Associates © 2004, All rights reserved
PROCESS OBJECT SHARINGPROCESS OBJECT SHARINGPROCESS OBJECT SHARINGPROCESS OBJECT SHARING
Process 1’sObject Table
Process 2’sObject Table
File A
File B
File C
File D
File E
Handle 1
Handle 2
Handle 3
Handle 4
Inheritable Inherited Handle 1
Handle 2
Handle 3
Handle 4Create File
Create File
Inherited
Not Inheritable
Not Inheritable
Inheritable
29JMH Associates © 2004, All rights reserved
PROCESS IDENTITIES (1 of 4)PROCESS IDENTITIES (1 of 4)PROCESS IDENTITIES (1 of 4)PROCESS IDENTITIES (1 of 4)
HANDLE GetCurrentProcess (VOID) Return: a “pseudo handle” which is not inheritable Can be used whenever a process needs its own handle
DWORD GetCurrentProcessId (VOID) Return: The process ID of the current process
30JMH Associates © 2004, All rights reserved
PROCESS IDENTITIES (2 of 4)PROCESS IDENTITIES (2 of 4)PROCESS IDENTITIES (2 of 4)PROCESS IDENTITIES (2 of 4)
HANDLE OpenProcess (DWORD dwAccess,BOOL fInherit,DWORD IDProcess)
Return: A process handle (not restricted as the “pseudo handle” is) or NULL
31JMH Associates © 2004, All rights reserved
PROCESS IDENTITIES (3 of 4)PROCESS IDENTITIES (3 of 4)PROCESS IDENTITIES (3 of 4)PROCESS IDENTITIES (3 of 4)
Parameters
dwAccess See the next slide
fInherit Specifies whether the new handle is inheritable
IDProcess Identifier of the process requiring a handle
32JMH Associates © 2004, All rights reserved
PROCESS IDENTITIES (4 of 4)PROCESS IDENTITIES (4 of 4)PROCESS IDENTITIES (4 of 4)PROCESS IDENTITIES (4 of 4)
dwAccess — Determines the operations you can perform on the handle, including:
SYNCHRONIZE Enables processes to wait for the process to terminate
PROCESS_ALL_ACCESS All of the access flags are set
PROCESS_TERMINATE You can terminate a process with the TerminateProcess
function PROCESS_QUERY_INFORMATION
The handle can be used by GetExitCodeProcess and GetPriorityClass to obtain process information
33JMH Associates © 2004, All rights reserved
TOPIC IVTOPIC IVTOPIC IVTOPIC IV
Process Termination and Synchronization
34JMH Associates © 2004, All rights reserved
EXITING A PROCESSEXITING A PROCESSEXITING A PROCESSEXITING A PROCESS
VOID ExitProcess (UINT nExitCode)
BOOL GetExitCodeProcess (HANDLE hProcess,LPDWORD lpdwExitCode)
The process identified by hProcess must have PROCESS_QUERY_INFORMATION access
lpdwExitCode points to the DWORD that receives the value STILL_ACTIVE is a possible value, meaning the process
has not terminated
35JMH Associates © 2004, All rights reserved
TERMINATING A PROCESSTERMINATING A PROCESSTERMINATING A PROCESSTERMINATING A PROCESS
BOOL TerminateProcess (HANDLE hProcess,UINT uExitCode)
The handle must have PROCESS_TERMINATE access The terminating function specifies the exit code Before you exit from a process, be certain to free all
resources that might be shared with other processes A process terminated with TerminateProcess will not
execute its SEH
36JMH Associates © 2004, All rights reserved
WAITING FOR A PROCESS TO WAITING FOR A PROCESS TO TERMINATE (1 of 4)TERMINATE (1 of 4)
WAITING FOR A PROCESS TO WAITING FOR A PROCESS TO TERMINATE (1 of 4)TERMINATE (1 of 4)
A simple, limited method of synchronizing with another process
Functions can wait for many different types of objects Wait for:
A single process The first of several specified processes All processes in a specified group
Specify an optional timeout period
The following functions are general purpose and can be used with many types of objects
37JMH Associates © 2004, All rights reserved
WAITING FOR A PROCESS TO WAITING FOR A PROCESS TO TERMINATE (2 of 4)TERMINATE (2 of 4)
WAITING FOR A PROCESS TO WAITING FOR A PROCESS TO TERMINATE (2 of 4)TERMINATE (2 of 4)
DWORD WaitForSingleObject (HANDLE hObject,DWORD dwTimeOut)
DWORD WaitForMultipleObjects (DWORD cObjects,LPHANDLE lphObjects,BOOL fWaitAll,DWORD dwTimeOut)
Return: The cause of the wait completion or OXFFFFFFFF for an error (use GetLastError for more information)
38JMH Associates © 2004, All rights reserved
WAITING FOR A PROCESS TO WAITING FOR A PROCESS TO TERMINATE (3 of 4)TERMINATE (3 of 4)
WAITING FOR A PROCESS TO WAITING FOR A PROCESS TO TERMINATE (3 of 4)TERMINATE (3 of 4)
Specify either a single process handle, hObject, or an array of cObjects referenced by lphObjects
cObjects should not exceed MAXIMUM_WAIT_OBJECTS
dwTimeOut is in milliseconds 0 means the function returns immediately after testing the
state of the specified objects Use INFINITE for no timeout (wait forever for a process to
terminate)
GetExitCodeProcess Determines the exit code of the process
39JMH Associates © 2004, All rights reserved
WAITING FOR A PROCESS TO WAITING FOR A PROCESS TO TERMINATE (4 of 4)TERMINATE (4 of 4)
WAITING FOR A PROCESS TO WAITING FOR A PROCESS TO TERMINATE (4 of 4)TERMINATE (4 of 4)
fWaitAll if TRUE specifies wait for all processes to terminate. Possible return values are:
WAIT_OBJECT_0 — The process terminated either in the case of WaitForSingleObject or in a special case of WaitForMultipleObjects with fWaitAll set to TRUE
WAIT_OBJECT_0 + n where 0 <= n < cObjects Subtract WAIT_OBJECT_0 from the return value to
determine which process terminated when waiting for any of a group of processes to terminate
WAIT_TIMEOUT — Timeout period elapsed before the wait could be satisfied
WAIT_ABANDONED — Not possible with processes
40JMH Associates © 2004, All rights reserved
TOPIC VTOPIC VTOPIC VTOPIC V
Process Environments and Security
41JMH Associates © 2004, All rights reserved
ENVIRONMENT BLOCKS AND ENVIRONMENT BLOCKS AND STRINGSSTRINGS
ENVIRONMENT BLOCKS AND ENVIRONMENT BLOCKS AND STRINGSSTRINGS
The environment blocks contains a sequence of strings of the form:
Name = Value
Each environment string is NULL-terminated Pass a parent’s environment to a child process by setting lpvEnvironment to NULL
Any process can interrogate or modify its environment variables or add new environment variables to the block
42JMH Associates © 2004, All rights reserved
ENVIRONMENT BLOCKS AND ENVIRONMENT BLOCKS AND STRINGS (1 of 2)STRINGS (1 of 2)
ENVIRONMENT BLOCKS AND ENVIRONMENT BLOCKS AND STRINGS (1 of 2)STRINGS (1 of 2)
DWORD GetEnvironmentVariable (LPCTSTR lpName,LPTSTR lpValue,DWORD cchValue)
BOOL SetEnvironmentVariable (LPCTSTR lpName,LPCTSTR lpValue)
43JMH Associates © 2004, All rights reserved
ENVIRONMENT BLOCKS AND ENVIRONMENT BLOCKS AND STRINGS (2 of 2)STRINGS (2 of 2)
ENVIRONMENT BLOCKS AND ENVIRONMENT BLOCKS AND STRINGS (2 of 2)STRINGS (2 of 2)
lpName — The variable name Variable is added to the block if it does not exist and the
value is not NULL If the value is NULL, the variable is removed from the block The “=” character cannot appear in a value string
GetEnvironmentVariable — Returns the length of the value string (0 on failure)
If lpValue is not long enough (as indicated by cchValue) then the return value is the number of characters actually required to hold the complete string
44JMH Associates © 2004, All rights reserved
PROCESS SECURITYPROCESS SECURITYPROCESS SECURITYPROCESS SECURITY
Normally, CreateProcess gives PROCESS_ALL_ACCESS rights
There are some specific rights: PROCESS_TERMINATE CREATE_THREAD CREATE_PROCESS DUPLICATE_HANDLE PROCESS_SET_INFORMATION PROCESS_QUERY_INFORMATION
45JMH Associates © 2004, All rights reserved
LAB 6–A (Part 1)LAB 6–A (Part 1)LAB 6–A (Part 1)LAB 6–A (Part 1)
Using multiple processes, write a program, grepMP, which will create one process for each file to be searched by executing the search program, grep, which is included with the solutions
Each process should have its standard output set to a temporary file by the parent process
You will need to place grep.exe in the same directory as grepMP
Do the same for cat.exe as it is used to list the search results from a temporary file
46JMH Associates © 2004, All rights reserved
LAB 6–A (Part 2)LAB 6–A (Part 2)LAB 6–A (Part 2)LAB 6–A (Part 2)
Write a program, timep, which will execute the rest of the command line and report on the elapsed time that the program requires to execute.
For example:
timep sortMM presdent.txt
would execute the command line:
sortMM presdent.txt You will need to look up and use the function GetProcessTimes
You may also want to use GetProcessWorkingSetSize
47JMH Associates © 2004, All rights reserved
LAB 6–A (Part 3)LAB 6–A (Part 3)LAB 6–A (Part 3)LAB 6–A (Part 3)
Use the timep program to compare two implementations of the same function (you may require large files to get meaningful results), such as:
atou and atouMM
cpW and cpCF
Do you get different results on NTFS and FAT file systems?
48JMH Associates © 2004, All rights reserved
LAB 6–BLAB 6–BLAB 6–BLAB 6–B
Write JobShell.c and JobMgmt.c which implment a simple job management system. JobShell prompts the user for one of three commands:
1. jobbg command which runs the specified command in the background and assigns it a “job number.”
2. jobs lists all the currently running jobs, giving the job number and the corresponding command line
3. kill n terminates job number n
Maintain the list of jobs in a shared file and protect that file with file. It is then possible to quit the job shell and restart it later.