Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 JMH Associates © 2004, All rights reserved Chapter 6 Process Management.

Similar presentations


Presentation on theme: "1 JMH Associates © 2004, All rights reserved Chapter 6 Process Management."— Presentation transcript:

1 1 JMH Associates © 2004, All rights reserved Chapter 6 Process Management

2 2 JMH Associates © 2004, All rights reserved OBJECTIVESOBJECTIVES 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

3 3 JMH Associates © 2004, All rights reserved TOPICSTOPICS Topic IWindows Processes and Threads Topic IIProcess Management Topic IIIObject Sharing and Handle Inheritance Topic IVProcess Termination and Synchronization Topic VProcess Environments and Security Lab 6-A Lab 6-B

4 4 JMH Associates © 2004, All rights reserved TOPIC I Windows Processes and Threads

5 5 JMH Associates © 2004, All rights reserved OVERVIEWOVERVIEW  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

6 6 JMH Associates © 2004, All rights reserved Windows 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

7 7 JMH Associates © 2004, All rights reserved THREADSTHREADS  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

8 8 JMH Associates © 2004, All rights reserved A PROCESS AND ITS THREADS Process Code Global Variables Process Heap Process Resources Open Files, Heaps, · · · Environment Block · · · Thread 1 TLS Stack Thread N TLS Stack

9 9 JMH Associates © 2004, All rights reserved FILE SEARCHING USING MULTIPLE PROCESSES 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 Searches Complete

10 10 JMH Associates © 2004, All rights reserved TOPIC II Process Management and Handle Inheritance

11 11 JMH Associates © 2004, All rights reserved 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

12 12 JMH Associates © 2004, All rights reserved 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)

13 13 JMH Associates © 2004, All rights reserved 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

14 14 JMH Associates © 2004, All rights reserved 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

15 15 JMH Associates © 2004, All rights reserved 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

16 16 JMH Associates © 2004, All rights reserved 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

17 17 JMH Associates © 2004, All rights reserved PROCESS CREATION (7 of 8) typedef struct _STARTUPINFO { /* Lots of information controlling the window */ DWORD dwFlags; HANDLE hStdInput; HANDLE hStdOutput; HANDLE hStdError; } STARTUPINFO;

18 18 JMH Associates © 2004, All rights reserved 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

19 19 JMH Associates © 2004, All rights reserved EXECUTABLE IMAGE AND 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

20 20 JMH Associates © 2004, All rights reserved EXECUTABLE IMAGE AND COMMAND LINE (2 of 3) Rules for lp ImageName :  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.

21 21 JMH Associates © 2004, All rights reserved EXECUTABLE IMAGE AND 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

22 22 JMH Associates © 2004, All rights reserved TOPIC III Object Sharing and Handle Inheritance

23 23 JMH Associates © 2004, All rights reserved INHERITABLE HANDLES (1 of 2) typedef struct SECURITY_ATTRIBUTES { DWORD nLength; LPVOID lpSecurityDescriptor; BOOL bInheritHandle; } SECURITY_ATTRIBUTES;

24 24 JMH Associates © 2004, All rights reserved 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

25 25 JMH Associates © 2004, All rights reserved 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

26 26 JMH Associates © 2004, All rights reserved 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)

27 27 JMH Associates © 2004, All rights reserved 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

28 28 JMH Associates © 2004, All rights reserved PROCESS OBJECT SHARING Process 1’s Object Table Process 2’s Object Table File A File B File C File D File E Handle 1 Handle 2 Handle 3 Handle 4 InheritableInheritedHandle 1 Handle 2 Handle 3 Handle 4Create File Inherited Not Inheritable Inheritable

29 29 JMH Associates © 2004, All rights reserved 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

30 30 JMH Associates © 2004, All rights reserved 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

31 31 JMH Associates © 2004, All rights reserved 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

32 32 JMH Associates © 2004, All rights reserved 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

33 33 JMH Associates © 2004, All rights reserved TOPIC IV Process Termination and Synchronization

34 34 JMH Associates © 2004, All rights reserved EXITING 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

35 35 JMH Associates © 2004, All rights reserved TERMINATING 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

36 36 JMH Associates © 2004, All rights reserved WAITING FOR A PROCESS TO 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

37 37 JMH Associates © 2004, All rights reserved WAITING FOR A PROCESS TO 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)

38 38 JMH Associates © 2004, All rights reserved WAITING FOR A PROCESS TO 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

39 39 JMH Associates © 2004, All rights reserved WAITING FOR A PROCESS TO 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

40 40 JMH Associates © 2004, All rights reserved TOPIC V Process Environments and Security

41 41 JMH Associates © 2004, All rights reserved ENVIRONMENT BLOCKS AND STRINGS 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

42 42 JMH Associates © 2004, All rights reserved ENVIRONMENT BLOCKS AND STRINGS (1 of 2) DWORD GetEnvironmentVariable (LPCTSTR lpName, LPTSTR lpValue, DWORD cchValue) BOOL SetEnvironmentVariable (LPCTSTR lpName, LPCTSTR lpValue)

43 43 JMH Associates © 2004, All rights reserved ENVIRONMENT BLOCKS AND 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

44 44 JMH Associates © 2004, All rights reserved PROCESS 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

45 45 JMH Associates © 2004, All rights reserved 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

46 46 JMH Associates © 2004, All rights reserved 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

47 47 JMH Associates © 2004, All rights reserved 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?

48 48 JMH Associates © 2004, All rights reserved LAB 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.


Download ppt "1 JMH Associates © 2004, All rights reserved Chapter 6 Process Management."

Similar presentations


Ads by Google