Windows Process Management

MP 64:2 4002 ,82 rebmetpeS , yadseuT 361 e gaP mf. 60hc_traH C H A P T E R 6 Process Management A process contains its own independent virtual address space with both code and data, protected from other processes. Each process, in turn, contains one or more independently executing threads. A thread running within a process can create new threads, create new independent processes, and manage communication and synchronization between the objects. By creating and managing processes, applications can have multiple, concurrent tasks processing files, performing computations, or communicating with other networked systems.

It is even possible to exploit multiple processors to speed processing. This chapter explains the basics of process management and also introduces the basic synchronization operations that will be used throughout the rest of the book. Windows Processes and Threads Every process contains one or more threads, and the Windows thread is the basic executable unit. Threads are scheduled on the basis of the usual factors: availability of resources such as CPUs and physical memory, priority, fairness, and so on.

Windows has supported symmetric multiprocessing (SMP) since NT4, so threads can be allocated to separate processors within a system. From the programmer’s perspective, each Windows process includes resources such as the following components: • One or more threads. • A virtual address space that is distinct from other processes’ address spaces, except where memory is explicitly shared. Note that shared memory-mapped files share physical memory, but the sharing processes will use different virtual addresses to access the mapped file. • One or more code segments, including code in DLLs. 63 MP 64:2 4002 ,82 rebmetpeS , yadseuT 461 e gaP mf. 60hc_traH 164 CHAPTER 6 PROCESS MANAGEM ENT • One or more data segments containing global variables. • Environment strings with environment variable information, such as the current search path. • The process heap. • Resources such as open handles and other heaps. Each thread in a process shares code, global variables, environment strings, and resources. Each thread is independently scheduled, and a thread has the following elements: • A stack for procedure calls, interrupts, exception handlers, and automatic storage. Thread Local Storage (TLS)—arrays of pointers giving each thread the ability to allocate storage to create its own unique data environment. • An argument on the stack, from the creating thread, which is usually unique for each thread. • A context structure, maintained by the kernel, with machine register values. Figure 6–1 shows a process with several threads. This figure is schematic and does not indicate actual memory addresses, nor is it drawn to scale. This chapter shows how to work with processes consisting of a single thread. Chapter 7 shows how to use multiple threads.

Note: Figure 6–1 is a high-level overview from the programmer’s perspective. There are numerous technical and implementation details, and interested readers can find out more in Inside Windows 2000 (Solomon and Russinovich). A UNIX process is comparable to a Windows process with a single thread. Threads, in the form of POSIX Pthreads, are a recent addition to UNIX implementations and are now nearly universally used. Stevens (1992) does not discuss threads; everything is done with processes. Needless to say, vendors and others have provided various thread implementations for many years; they are not a new concept.

Pthreads is, however, the most widely used standard, and proprietary implementations are obsolete. Figure 6–1 A Process and Its Threads Process Creation The fundamental Windows process management function is , which creates a process with a single thread. It is necessary to specify the name of call. an executable program file as part of the It is common to speak of parent and child processes, but these relationships are not actually maintained by Windows. It is simply convenient to refer to the process that creates a child process as the parent. has ten parameters to support its flexibility and power. it is Initially, it is simple to use default values. Just as with parameters. Related functions appropriate to explain all the then become easier to understand. ; rather, two separate Note first that the function does not return a handles, one each for the process and the thread, are returned in a structure speccreates a new process with a primary thread. ified in the call. The example programs are always very careful to close both of these handles when they are no longer needed in order to avoid resource leaks; a common defect is to neglect to close the thread handle.

Closing a thread handle, for instance, does not function only deletes the reference to the terminate the thread; the . thread within the process that called ssecorPet aerC eliFetaerC E L DN A H egarotS lacoL daerhT ssec orPetaerC N daerhT ssecorP etaerC eldn aHesolC kcatS ssec orPetaerC secruoseR ssecorP kcolB tnemnorivnE selbairaV labolG paeH ssecorP ssecorP seliF nepO · · · · · · spaeH edoC egarotS lacoL daerhT s s ec or P et a er C 1 daerhT kcatS MP 64:2 4002 ,82 rebmetpeS , yadseuT 561 e gaP mf. 60hc_traH PROCESS CREATION 165 s sec or Pe tae rC

Parameters Some parameters require extensive explanations in the following sections, and many are illustrated in the program examples. and (this is an and not an ) together specify the executable program and the command line arguments, as explained in the next section. and point to the process and thread security atvalues imply default security and will be used until tribute structures. Chapter 15, which covers Windows security. indicates whether the new process inherits copies of the calling process’s inheritable open handles (files, mappings, and so on).

Inherited handles have the same attributes as the originals and are discussed in detail in a later section. combines several flags, including the following. ELOSNOC _WEN_ETAERC SSECORP_DEHC ATED • and are mutually exclusive; don’t set both. The first flag creates a process without a console, and the second flag gives the new process a console of its own. If neither flag is set, the process inherits the parent’s console. daerhTemuseR DEDNEPSUS_ET AERC • indicates that the primary thread is in a suspended state is called. and will run only when RTSTPL ofnIcor Ppl NOITAMROFN I_SSECORPPL ,of nIputratSpl OF NIPUTRATSPL ,riDruCpl RTSTCPL ,tnemnoriv nEpl DIOVPL ,sgalFnoita erCwd DROWD ,seldnaHti rehnIb LOOB ,daerhTa spl SETUBIRTTA _YTIRUCESPL ,ssecorPa spl SETUBIRTTA _YTIRUCESPL ,eniLdnamm oCpl RTSTPL , emaNnoitacilpp Apl RTSTCPL ( ssecorP etaerC LOOB eniLdnammoCpl LLU N da er hT as pl s se co rPa sp l MP 64:2 4002 ,82 rebmetpeS , yadseuT 661 e gaP mf. 60hc_traH 166 CHAPTER 6 PROCESS MANAGEM ENT RTS TCP L emaNnoitacilppApl s el dna Ht ir eh nI b sgalFnoitae rCwd EU RT Return: created. only if the process and thread are successfully

Several of the flags control the priority of the new process’s threads. The possible values are explained in more detail at the end of Chapter 7. For now, just use . the parent’s priority (specify nothing) or points to an environment block for the new process. If , the process uses the parent’s environment. The environment block contains name and value strings, such as the search path. specifies the drive and directory for the new process. If , the parent’s working directory is used. specifies the main window appearance and standard device handles for the new process.

Use the parent’s information, which is obtained from . Alternatively, zero out the associated structure . To specify the standard input, output, and error before calling , , and handles, set the standard handler fields ( ) in the structure. For this to be effective, also set member, , to , and set another all the handles that the child process will require. Be certain that the handles are flag is set. The inheritable and that the Inheritable Handles subsection gives more information and an example. specifies the structure for containing the returned process, structure is as thread handles, and identification.

The follows: Why do processes and threads need handles in addition to IDs? The ID is unique to the object for its entire lifetime and in all processes, whereas a given process may have several handles, each having distinct attributes, such as LLUN LL UN t u pt u Od tS h t u pn I dt S h S EL DN AH DT SE S U_ FT RA TS OFNIPUTR ATS SSALC_YTI ROIRP_LAMRON NO I TA MR O FN I_ SS E CO RP se ldna Htir ehnI b sse corP etae rC ;NOITAMROFN I_SSECORP } ;dIdae rhTwd DROWD ;dIssec orPwd DROWD ;dae rhTh ELDNAH ;ssec orPh ELDNAH { NOITAMROF NI_SSECORP tcu rts fedepyt s ga lF wd O FN IP UT RA TS OFN IP UT RA TS r or rE dt Sh

PUORG_SSECORP _WEN_ETAERC s sec or Pet ae rC ofnIputr atSteG k aer b- lr tC MP 64:2 4002 ,82 rebmetpeS , yadseuT 761 e gaP mf. 60hc_traH PROCESS CREATION 167 • specifies that the new process is the root of a new process group. All processes in a group receive a console control signal or ) if they all share the same console. Console control ( handlers were described in Chapter 4 and illustrated in Program 4–5. These process groups have similarities to UNIX process groups and are described later in this chapter. of nIpu trat Spl tn emnorivnEpl o fn I co rP pl r iD ruC pl c- lr tC

The UNIX and Windows process models are considerably different. First, Windows has no equivalent to the UNIX function, which makes a copy of the is difficult to parent, including the parent’s data space, heap, and stack. emulate exactly in Windows, and, while this may seem to be a limitation, is also difficult to use in a multithreaded UNIX system because there are numerous problems with creating an exact replica of a multithreaded system with exact copies of all threads and synchronization objects, especially on an SMP system. Therefore, , by itself, is not really appropriate in any multithreaded system. s, however, similar to the common UNIX sequence of successive calls to and (or one of five other functions). In contrast to Windows, the search directories in UNIX are determined entirely by the environment variable. As previously mentioned, Windows does not maintain parent-child relationships among processes. Thus, a child process will continue to run after the creating parent process terminates. Furthermore, there are no process groups in Windows. There is, however, a limited form of process group that specifies all the processes to receive a console control event.

Windows processes are identified both by handles and by process IDs, whereas UNIX has no process handles. Specifying the Executable Image and the Command Line eni Ld nam mo Cpl Either or name. The rules are as follows. specifies the executable image eniLd nammoCpl • Otherwise, the executable is the first token in LLUN emaNnoitacilp pApl • , if not , is the name of the executable. Quotation marks can be used if the image name contains spaces. More detailed rules are described below. . HTAP kr of krof ss eco rP eta er C c ex e k rof ssecor Petae rC em aN noi ta cil pp Apl l ce xe

MP 64:2 4002 ,82 rebmetpeS , yadseuT 861 e gaP mf. 60hc_traH 168 CHAPTER 6 PROCESS MANAGEM ENT security access. For this reason, some process management functions require IDs, and others require handles. Furthermore, process handles are required for the general-purpose, handle-based functions. Examples include the wait functions discussed later in this chapter, which allow waiting on handles for several different object types, including processes. Just as with file handles, process and thread handles should be closed when no longer required. Note: The new process obtains environment, working directory, and other incall.

Once this call is complete, any changes formation from the in the parent will not be reflected in the child process. For example, the parent call, but the child might change its working directory after the process working directory will not be affected, unless the child changes its own working directory. The two processes are entirely independent. k ro f ss ecor Pet aer C k rof • If is not , it specifies the executable module. Specify the full path and file name, or use a partial name and the current drive and directory will be used; there is no additional searching.

Include the or , in the name. file extension, such as • If the string is , the first white-space-delimited is the program name. If the name does not contain a token in full directory path, the search sequence is as follows: 1. The directory of the current process’s image 2. The current directory The new process can obtain the command line using the usual mechanism, or it can invoke to obtain the command line as a single string. Notice that the command line is not a constant string. This is consistent with parameters to the main program are not constant.

A the fact that the program could modify its arguments, although it is advisable to make any changes in a copy of the argument string. definition The new process is not required to be built with the same as as that of the parent process. All combinations are possible. Using discussed in Chapter 2 is helpful in developing code for either UNICODE or ASCII operation. Inheritable Handles Frequently, a child process requires access to an object referenced by a handle in the parent; if this handle is inheritable, the child can receive a copy of the parent’s open handle.

The standard input and output handles are frequently shared with the child in this way. To make a handle inheritable so that a child receives and can use a copy requires several steps. flag on the call determines whether The the child process will inherit copies of the inheritable handles of open files, vgra nia mt_ EDOCINU HTA P 5. The directories as specified in the environment variable yrotceriDswo dniWteG 4. The Windows directory, which is retrievable with -met sySteG 3. The Windows system directory, which can be retrieved with emaNnoi tacilppApl e maN noi tac ilpp Apl ssecorPe taerC LLUN en iL dn am mo Ct eG LLUN TAB . n iLd nam moCp l eniLdnammoCpl emaNn oitacilppApl EXE. MP 64:2 4002 ,82 rebmetpeS , yadseuT 961 e gaP mf. 60hc_traH PROCESS CREATION 169 Usually, only is specified, with . Nonetheless, there are detailed rules for being . emaN noitacilppApl seldnaHtire hnIb vg r a yr otceriD LLUN A child process still needs to know the value of an inheritable handle, so the parent needs to communicate handle values to the child using an interprocess communication (IPC) mechanism or by assigning the handle to standard I/O in structure, as is done in the first example of this chapter the (Program 6–1) and in several additional examples throughout the book.

This is generally the preferred technique because it allows I/O redirection in a standard way and no changes are needed in the child program. Alternatively, nonfile handles and handles that are not used to redirect standard I/O can be converted to text and placed in a command line or in an environment variable. This approach is valid if the handle is inheritable because both parent and child processes identify the handle with the same handle value. Exercise 6–2 suggests how to demonstrate this, and a solution is presented on the book’s Web site. The inherited handles are distinct copies.

Therefore, a parent and child might be accessing the same file using different file pointers. Furthermore, each of the two processes can and should close its own handle. Figure 6–2 shows how two processes can have distinct handle tables with two distinct handles associated with the same file or other object. Process 1 is the parent, and Process 2 is the child. The handles will have identical values in both foe zis eldnaHt irehnIb /* . desuer eb nac as . elbatirehn I */ ;)… ,as& ,.. .( eliFetaerC = 3h /* . elbatir ehni toN */ 😉 … ,LLUN ,.. .( eliFetaerC = 2h /* . el batirehnI */ ; ) … ,as& ,.. ( eliFetaerC = 1h … ;} EURT ,LL UN ,)SETUBIRTT A_YTIRUCES(foe zis{ = as S ETUBIRTTA_YTIR UCES ;3h ,2h ,1h EL DNAH SET UBIRTTA_YTIRUC ES htg neL n )SE TUBIRTTA_YTIRU CES( EURT SETUBIRT TA_YTIRUCES ;LLUN MP 64:2 4002 ,82 rebmetpeS , yadseuT 071 e gaP mf. 60hc_traH 170 CHAPTER 6 PROCESS MANAGEM ENT processes, and so on. The flag can be regarded as a master switch applying to all handles. It is also necessary to make an individual handle inheritable; it is not done by structure default. To create an inheritable handle, use a at creation time or duplicate an existing handle. structure has a flag, , that The .

Also, recall that should be set to should be set to . The following code segment shows how an inheritable file or other handle is typically created. In this example, the security descriptor within the security Chapter 15 shows how to include a security descriptor. attributes structure is O F NI P U T R A TS Figure 6–2 Process Handle Tables processes if the child’s handle has been inherited, as is the case with Handles 1 and 3. On the other hand, the handle values may be distinct. For example, there are two handles for File D, where Process 2 obtained a handle by calling rather than by inheritance.

Finally, as is the case with Files B and E, one process may have a handle to an object while the other does not. This would be the case when the child process creates the handle or when a handle is duplicated from one process to another, as described in the upcoming Duplicating Handles section. Process Handle Counts A common programming error is to neglect to close handles when they are no longer needed; this can result in resource leakage, which in turn can degrade performance, cause program failures, and even impact other processes. NT 5. added a new function that allows you to determine how many handles any process has open. In this way, you can monitor your own process or other processes. Here is the function definition, which is self-explanatory: eliF etaerC 1 eldnaH 2 eldnaH 3 eldnaH 4 eldnaH eliFetaerC eliFetaerC e lb aT tc e jbO s’2 ssecorP d lihC detirehn I detirehn I )tnuoCeldna Hwdp DROWDP ,ssec orPh ELDNAH ( t nuoCeldnaHssec orPteG LOOB C eliF D eliF A eliF B eliF E eliF MP 64:2 4002 ,82 rebmetpeS , yadseuT 171 e gaP mf. 60hc_traH PROCESS HANDLE COUNTS 171 elbatirehnI toN elbatirehnI toN elb aT tc ejbO s’1 ss ec orP elbatirehnI lbatirehnI tneraP 1 eldnaH 2 eldnaH 3 eldnaH 4 eldnaH Parameters determines the handle’s access to the process. Some of the values are as follows. and -tixEteG ssal CytiroirPteG ssecorP edoC NOITAMR OFNI_YREUQ_SSE CORP • ssecorPetani mreT ETANIMRET_SSE CORP • SSECCA_LLA_SSE CORP • EZINORH CNYS • —This flag enables processes to wait for the process to terminate using the wait functions described later in this chapter. —All the access flags are set. —It is possible to terminate the process with the function. —The handle can be used by to obtain process information. . LLUN Return: A process handle, or n failure – t ne r ru C t eG actually returns a pseudohandle and is not inheritable. This value can be used whenever a process needs its own handle. You create a real process handle from a process ID, including the one returned by , by using the function. As is the case with all sharable objects, the open call will fail if you do not have sufficient security rights. )DIOV( dIssecorPtnerr uCteG DROWD )DIOV( ssecorPtnerru CteG ELDNAH )dIssec orPwd DROWD ,eldnaHti rehnIb LOOB ,sseccAderi seDwd DROWD ( ssecorP nepO ELDNAH ssecorPnepO MP 64:2 4002 ,82 rebmetpeS , yadseuT 271 e gaP mf. 0hc_traH 172 CHAPTER 6 PROCESS MANAGEM ENT Process Identities A process can obtain the identity and handle of a new child process from the structure. Closing the child handle does not, of course, destroy the child process; it destroys only the parent’s access to the child. A pair of functions is used to obtain current process identification. ssecorPtnerru CteG N OI TA MR OF N I_ SS EC OR P s s e c c Ad e r i s e D w d dIsse corP Duplicating Handles The parent and child processes may require different access to an object identified by a handle that the child inherits.

A process may also need a real, inheritable process handle—rather than the pseudohandle produced by —for use by a child process. To address this issue, the parent process can create a duplicate handle with the desired access and inheritability. Here is the function to duplicate handles: points to a copy of the original handle, is a handle in the process indicated by and must have access; will fail if the source handle does not exist in the source process. , is valid in the target The new handle, which is pointed to by . Note that three processes are involved, process, including the calling process.

Frequently, these target and source processes are the . Also notice calling process, and the handle is obtained from that it is possible to create a handle in another process; if you do this, you then need a mechanism for informing the other process of the new handle’s identity. can be used for any handle type. is not overridden by in If , it has many possible values (see the MSDN library on-line help). Upon completion, . -tn erruCteG SS EC CA _E MA S_ ET AC IL PU D eldnaHssecorPtegraTh eldn aHteg raThpl eldnaHetacilpuD EL D N A H_ P U D _S S E C OR P e l d n aH s s e co r P e cr u o S h e ldnaH ecruo Sh eldn aHecr uoSh eld naH teg raT hpl Eema NeliFeludoMteG ssecorPtnerruCteG )snoi tpOwd DROWD ,eldnaHti rehnIb LOOB ,sseccAderi seDwd DROWD ,eldnaHtegraTh pl ELDNAHPL ,el dnaHssecorPteg raTh ELDNAH ,eldnaHecr uoSh ELDNAH ,el dnaHssecorPecr uoSh ELDNAH ( eldnaHeta cilpuD LOOB EXE. eludo Mh emaNeliFeludoMteG MP 64:2 4002 ,82 rebmetpeS , yadseuT 371 e gaP mf. 60hc_traH DUPLICATING HANDLES 173 specifies whether the new ha ndle is inherita ble. is the identifier of the process requiring a handle. Finally, a running process can determine the full pathname of the executable or , using a used to run it with value for the parameter.

A call from within a DLL will return the file that uses the DLL. DLL’s file name, not that of the snoitpOwd s se cc Ad er is eD wd eldn aHetacilpuD dIssecorPwd e ldn aH tir ehn Ib ssecorP LLUN Reminder: The Windows kernel maintains a reference count for all objects; this count represents the number of distinct handles referring to the object. This count is not available to the application program, however. An object cannot be destroyed until the last handle is closed and the reference count becomes zero. Inherited and duplicate handles are both distinct from the original handles and are represented in the reference count.

Program 6–1, later in the chapter, uses inheritable handles. On the other hand, a handle passed from one process to another through some form of IPC is not a distinct handle, so if one process closes the handle, the handle cannot be used by any other process. This technique is rarely used, but Exercise 6–2 uses IPC to send the value of the inherited handle to another process. Next, it is necessary to learn how to determine whether a process has terminated. Exiting and Terminating a Process After a process is complete, the process, or more accurately, a thread running in with an exit code. the process, can call This function does not return.

Rather, the calling process and all its threads terminate. Termination handlers are ignored, but there will be detach calls to (see Chapter 5). The exit code is associated with the process. A from the main program, with a return value, will have the same effect as calling with the return value as the exit code. to determine the exit code. Another process can use nrut er sseccAderiseD wd sseco rPedoCtixEteG )edoCtixEu TNIU( sseco rPtixE DIOV )edoCtixE pl DROWDPL ,ssec orPh ELDNAH ( ssecorPedoCt ixEteG LOOB ssecorPtixE SSE CCA_EMAS_ETACI LPUD • ECRU OS_ESOLC_ETACI LPUD MP 64:2 4002 ,82 rebmetpeS , yadseuT 471 e gaP mf. 0hc_traH 174 CHAPTER 6 PROCESS MANAGEM ENT is any combination of two flags. causes the source handle to be closed. to be ignored. • snoit pOwd ssecorP tixE niaMl lD causes Caution: Before exiting from a process, be certain to free all resources that might be shared with other processes. In particular, the synchronization resources of Chapter 8 (mutexes, semaphores, and events) must be handled carefully. SEH call can be in the (Chapter 4) can be helpful in this regard, and the and handlers are not executed when handler. However, is called, so it is not a good idea to exit from inside a program. s especially risky because the terminated process will not functions. Console have an opportunity to execute its SEH or DLL control handlers (Chapter 4 and later in this chapter) are a limited alternative, allowing one process to send a signal to another process, which can then shut itself down cleanly. Program 6–3 shows a technique whereby processes cooperate. One process sends a shutdown request to a second process, which proceeds to perform an orderly shutdown. UNIX processes have a process ID, or , comparable to the Windows process ID. is similar to , but there are no

Windows equivalents to and because Windows has no process parents or groups. Conversely, UNIX does not have process handles, so it has no functions comparable to or . UNIX allows open file descriptors to be used after an if the file descriptor flag set. This applies only to file descriptors, does not have the which are then comparable to inheritable file handles. s s e co r P t ix E c ex e sse cor Pne pO s sec orP tne rru Cte G dip gte g di ppt eg dI ss eco rP tne rr uCt eG dip d ipt eg UNIX , actually in the C library, is similar to another process, signal it with . LL IKG IS tixe EVITCA_LLITS e do Cti xE pl -R OFN I_YR EUQ_ SSE CORP sec orPtixE ni aM l lD t pe c x e _ _ ss eco rPn ep O s seco rPh )edo CtixEu TNIU ,ssec orPh ELDNAH ( ssecorPeta nimreT LOOB c ex e -n o- e so lc yllanif__ MP 64:2 4002 ,82 rebmetpeS , yadseuT 571 e gaP mf. 60hc_traH E XI TI N G A N D TE R M IN A T I NG A P RO C ES S 175 The process identified by must have access (see , discussed earlier). points to the that receives the value. One possible value is , meaning that the process has not terminated. Finally, one process can terminate another process if the handle has access. The terminating function also specifies the exit code. ETANIMRET_SSECORP ss e co rP et an i mr eT ssec orPtixE

DROWD NOI TA M ; to terminate ) or an array of distinct object Specify either a single process handle ( . , the size of the array, handles in the array referenced by (defined as 64 in ). should not exceed is the time-out period in milliseconds. A value of 0 means that the function returns immediately after testing the state of the specified H. TNNIW FFFFFFFFX0 s dn oce si ll iMw d STCEJBO_ TIAW_MUMIXAM tn uoCn seldnaHp l tcejbOh )sdnocesil liMwd DROWD ,ll AtiaWf LOOB ,seldnaHpl* E LDNAH TSNOC ,t nuoCn DROWD ( stc ejbOelpitluMro FtiaW DROWD )sdnocesil liMwd DROWD ,tce jbOh ELDNAH ( tcejbOelgniSro FtiaW DROWD orrEtsaLte G MP 64:2 4002 ,82 rebmetpeS , yadseuT 671 e gaP mf. 60hc_traH 176 CHAPTER 6 PROCESS MANAGEM ENT Waiting for a Process to Terminate The simplest, and most limited, method of synchronizing with another process is to wait for that process to complete. The general-purpose Windows wait functions introduced here have several interesting features. • The functions can wait for many different types of objects; process handles are just the first use of the wait functions. • The functions can wait for a single process, the first of several specified processes, or all processes in a group to complete. There is an optional time-out period. The two general-purpose wait functions wait for synchronization objects to become signaled. The system sets a process handle, for example, to the signaled state when the process terminates or is terminated. The wait functions, which will get lots of future use, are as follows: Return: The cause of the wait completion, or for more information). error (use for an Environment Blocks and Strings Figure 6–1 includes the process environment block. The environment block contains a sequence of strings of the form Each environment string, being a string, is – terminated, and the entire – terminated. s one example of a commonly block of strings is itself used environment variable. to To pass the parent’s environment to a child process, set in the call. Any process, in turn, can interrogate or modify its environment variables or add new environment variables to the block. tn e mn or i vn E pl s se co rP ed oCt ix Et eG Determine the exit code of a process using described in the preceding section. HTAP L LUN LLUN ssecorPetaerC 0_DEN ODNABA_TIAW • is not possible with processes. This value is discussed in Chapter 8 along with mutex handles. , as EZINORHCNYS DELIAF_TIAW •

T UOEMIT_TIAW • indicates that the time-out period elapsed before the wait could be satisfied by signaled handle(s). have indicates that the call failed; for example, the handle may not access. 0 _D E N O D N A B A _ T I A W 0_TCEJ BO_TIAW tnu oCn n 0 n+0_ TCEJBO_TIAW • , where ? < . Subtract from the return value to determine which process terminated when waiting for any of a group of processes to terminate. If several handles are signaled, the is a returned value is the smallest possible value. possible base value when using mutex handles; see Chapter 8. E URT llAtiaWf pecial case of -roF tiaW stcejbOelpit luMroFtiaW t nu oC n t cej bO el gn iS 0_ TCEJBO_TIAW • means that the handle is signaled in the case of or all objects are simultaneously signaled in the with set to . E TI NI F NI E U RT MP 64:2 4002 ,82 rebmetpeS , yadseuT 771 e gaP mf. 60hc_traH ENVIRONMENT BLOCKS AND STR INGS 177 objects, thus allowing a program to poll for process termination. Use for no time-out to wait until a process terminates. , a parameter of the second function, specifies (if ) that it is necessary to wait for all processes, rather than only one, to terminate.

The possible successful return values for this function are as follows. e ulaV = emaN l lA t i aW f LLUN is the variable name. On setting a value, the variable is added to the . If, on the other hand, the block if it does not exist and if the value is not , the variable is removed from the block. The “ ” character cannot value is appear in a value string. returns the length of the value string, or on buffer is not long enough, as indicated by , then failure. If the the return value is the number of characters actually required to hold the (Chapter 2) uses a similar complete string. Recall that mechanism.

Process Security Normally, gives rights. There are, , however, several specific rights, including , , , , and . In particular, it can be useful to limit rights to the parent process given the frequently mentioned dangers of terminating a running process. Chapter 15 describes security attributes for processes and other objects. ETANIMRET_SSE CORP DAERH T_ETAERC ELDNAH_ETACI LPUD N O I T AM R O F N I _ T E S _S S E C O R P E T A N IM R E T _ S S E C O RP S S E C OR P _ E T A E R C N OI T A M R O FN I _ Y R EU Q _ S S EC O R P S S E C C A _ L L A _ S S E CO R P s s e co r P e t a e r C

UNIX waits for process termination using and , but there are no can poll (there is a nonblocking option). These time-outs even though functions wait only for child processes, and there is no equivalent to the multiple wait on a collection of processes, although it is possible to wait for all processes in a process group. One slight difference is that the exit code is returned with and , so there is no need for a separate function equivalent to . e lb ai ra V tn em n or iv n Et eG v net eg UNIX also supports environment strings similar to those in Windows. the C library) has the same functionality as in except 0 eulaVhcc -t ixE teG ti aw = di p t ia w LLUN yr ot ce r iD tn er ru Ct eG t ia w )eul aVhcc DROWD ,eul aVpl RTSTPL ,emaNpl RTSTCPL ( elb airaVtnemnoriv nEteG DROWD )eulaVpl RTSTCPL ,emaNpl RTSTCPL ( el bairaVtnemnori vnEteS LOOB d i p t i aw eulaVpl e l b ai r a V t n em n o r i vn E t e G MP 64:2 4002 ,82 rebmetpeS , yadseuT 871 e gaP mf. 60hc_traH 178 CHAPTER 6 PROCESS MANAGEM ENT The two functions used to get and set variables are as follows: ssec orP edo C di pti aw L LU N emaN pl Example: Parallel Pattern Searching Now is the time to put Windows processes to the test.

This example, , creates processes to search for patterns in files, one process per search file. The utility, although the pattern search program is modeled after the UNIX technique would apply to any program that uses standard output. The search program should be regarded as a black box and is simply an executable program to be controlled by a parent process. The command line to the program is of the form The program, Program 6–1, performs the following processing: • Each input file, to , is searched using a separate process running the same executable. The program creates a command line of the form . The handle of the temporary file, specified to be inheritable, is assigned to the field of the new process’s start-up information structure. • As soon as all searches are complete, the results (temporary files) are utility (Program displayed in order, one at a time. A process to execute the 2–3) outputs the temporary file. • The program uses the process exit code to determine whether a specific process detected the pattern. Figure 6–3 shows the processing performed by Program 6–1. STC EJBO_TIAW_MUMI XAM stcejbOelpi tluMroFtiaW • is limited to dles, so it is called multiple times. ac stcejbO elpitluMroFtia W • Using to complete. , the program waits for all search processes (64) han- p er g PMpe rg vnetup perg NF … 2F 1F nre ttap PMperg p erg elba ira Vtn emn ori vnE teS NF MP 64:2 4002 ,82 rebmetpeS , yadseuT 971 e gaP mf. 60hc_traH EXAMPLE: PARALLEL PATTER N SEARCHING 179 that the programmer must be sure to have a sufficiently large buffer. , , and (not in the C library) are different ways to add, change, and remove variables and their values, with functionality equivalent to . v ne t es n u v ne t es 1F KF nrettap tuptuOdtSh /* . e ma n e li f pm et f o y ar ra o t re t ni oP * / ;e l iF co rP * EL I FC OR P ; E LI FC OR P }; ] HT AP _X AM [ el i Fp me T RA HC T { tc ur ts f e de py t / * . s e ld na h co rp fo y ar ra n a o t re tn io P * / ;c or Ph * E LD NA H ; ed o Cx E ,c or Pi DR OW D ;o fn I ss ec or P NO I TA MR OF NI _S S EC OR P ; pU tr at S , hc ra eS pU t ra tS O FN IP U TR AT S ; ]0 01 + HT AP _X AM [ e ni Ld na mm oC RA HC T ;} EU R T ,L LU N ,) S ET UB IR TT A_ Y TI RU CE S( f o ez is { / * . e ld na h e lb at ir eh ni ro f AS * / = A St uO dt S SE T UB IR TT A_ YT I RU CE S ; el iF pm eT h E LD NA H { / * . tl us er eh t ev ie ce r o t ,y ro tc er i d tn er ru c e ht n i , e li f yr ar op m et a n ev ig s i s se co rp h c aE . en il d n am mo c e ht n o el if hc ae h cr ae s o t ss ec or p e ta ra pe s a e ta er C * / ) ][ v gr a RT S TP L ,c gr a D RO WD ( ni am t _ tn i “h . g n hT yr vE ” ed u lc ni # / * . dn am mo c pe rg fo n oi sr ev ss ec or p el p it lu M * / /* . P Mp er g . 6 r e tp ah C * / ssecorPtixE } ;tcejbOelgniSroFtiaW )]i[ pmeT tac( ssecorPetaerC { )++i ;N =< i ;1 = i( rof /* stluser hcraes yalpsiD */ ··· ;stcejbOelpitluMroFtiaW telpmoC sehcraeS llA ssecorPtixE ]1+N[ vgra nrettap perg · · · ssecorPtixE ]3[ vgra nrettap perg } )]1+i[ vgra nrettap perg( ssecorPetaerC )]i[ pmeT( eliFetaerC = tuOdtSh. pUtratS { )++i ;N =< i ;1 = i( rof ssecorPtixE ]2[ vgra nrettap perg ]1+N[ vgra ,… ,]2[ vgra ,]1[ vgra ss ec or P t n e r aP MP 64:2 4002 ,82 rebmetpeS , yadseuT 081 e gaP mf. 60hc_traH 180 Program 6–1 CHAPTER 6 :PM perg Figure 6–3 File Searching Using Multiple Processes PROCESS MANAGEM ENT Parallel Searching } ; )d ae r hT h. of nI ss e co rP ( el dn a He so lC 😉 ss ec o rP h. f nI ss e co rP ( el dn a He so lC 😉 E TI NI FN I ,s s ec or Ph . o fn I ss ec or P( t c ej bO el gn iS r oF ti aW ; )o fn I ss ec or P& , p Ut ra tS & ,L L UN , LL UN , 0 , EU RT , LL UN ,L LU N ,e ni L dn am mo C ,L L UN ( ss ec or P et ae rC ; )e li Fp me T. ] co rP i[ e li F co rP , )” t a c” ( T_ , )” s% s% ” ( T_ , en iL d na mm oC ( ft n ir pt s_ /* . t uo dt s es u s es se co rp el pi tl uM * / ; )t uo dt s( hs ul ff ; )] 2 + c or Pi [ vg r a ,) “n : s% ” ( T_ ( ft ni r pt _ )3 > c g ra ( fi / * . tl us er ts iL – – de t ce te d sa w n re tt aP */ { ) 0= =e do Cx E & & )e do Cx E & ,] co rP i[ co rP h( ss ec o rP ed oC ti xE t eG ( fi { )+ + co rP i ;2 – cg ra < c or P i ;0 = c or P i( r of / * “. ta c ” gn is u tu p tu o dt s ot tn es s el if tl us eR */ ; )E T IN IF NI , EU R T ,] co rP i[ co rP h& , )c or P i – 2 – cg r a ,S TC EJ BO _ TI AW _M UM IX A M( n im / * se ss ec o rp f o # eg r al a s wo ll A * / ( st ce j bO el pi tl uM r oF ti aW )S T CE JB O_ TI AW _ MU MI XA M =+ co rP i ;2 – cg ra < c or P i ;0 = c or P i( r of / * . t el pm oc o t m eh t ro f ti a W . g ni nn ur ll a er a se s se co rP */ ;s se co rP h . o fn Is se co r P = ]c or Pi [ c or Ph 😉 da er hT h . o fn Is se co r P( e ld na He s ol C 😉 el iF p me Th ( el dn a He so lC /* . se ld n ah d et na wn u e so lC */ ; )o fn Is se co r P& , hc ra eS p Ut ra tS & ,L L UN , LL UN , 0 , EU RT , LL UN ,L LU N ,e ni L dn am mo C ,L L UN ( ss ec or P et ae rC /* . en il dn am mo c eh t e tu ce xe o t s se co rp a et ae rC */ } ; )E LD NA H _T UP NI _D TS ( e ld na Hd tS t eG = t up nI d tS h. c ra eS p Ut ra tS ; el iF pm e Th = r or rE d tS h. hc ra eS p Ut ra tS ;e li Fp me T h = tu pt uO d tS h. hc ra eS p Ut ra tS ; SE LD N AH DT SE SU _F T RA TS = s ga l Fw d. hc ra eS p Ut ra tS 😉 LL U N ,L AM RO N_ E TU BI RT TA _E L IF , SY AW LA _ ET AE RC ,A St uO d tS & ,E TI RW _ ER AH S_ EL IF | DA ER _E RA H S_ EL IF , ET IR W_ C IR EN EG , el iF pm eT . ]c or Pi [ el i Fc or P( e li F et ae rC /* e l ba ti re hn i s i el dn ah s i hT * / = el i Fp me Th /* . s tl us er h c ra es r oF * / ; )e li Fp me T . ] co rP i[ e l iF co rP , 0 , )” mt g” ( T _ ,) “. ( T _ ( em aN el iF p me Tt eG 😉 ] 2 + co rP i[ vg ra , ]1 [ v gr a ,) ” pe r g” ( T_ ,) “s % s% s% ” ( T_ , en iL d na mm oC ( ft n ir pt s_ { )+ + co rP i ;2 – cg ra < c or P i ;0 = c or P i( r of /* . el if h c ae r of s se c or p “p er g” et ar ap es a et ae rC */ 😉 )E LD N AH ( fo ez is * )2 – c gr a (( c ol la m = c or Ph ; )) EL IF CO RP ( f oe zi s * ) 2 – cg ra (( co ll am = e l iF co rP 😉 pU tr at S &( o fn Ip ut r at St eG ; )h c ra eS pU tr at S &( o fn Ip ut r at St eG EXAMPLE: PARALLEL PATTER N SEARCHING 181 MP 64:2 4002 ,82 rebmetpeS , yadseuT 181 e gaP mf. 60hc_traH Processes in a Multiprocessor Environment

In Program 6–1, the processes and their primary (and only) threads run almost totally independently of one another. The only dependence is created at the end of the parent process as it waits for all the processes to complete so that the output files can be processed sequentially. Therefore, the Windows scheduler can and will run the process threads concurrently on the separate processors of an SMP system. This can result in substantial performance improvement when performance is measured as elapsed time to execute the program, and no explicit actions are required to get the performance improvement.

Appendix C shows some typical results. The performance improvement is not linear in terms of the number of processors due to overhead costs and the need to output the results sequentially. Nonetheless, the improvements are worthwhile and result automatically as a consequence of the program design, which delegates independent computational tasks to independent processes. It is possible, however, to constrain the processes to specific processors if you wish to be sure that other processors are free to be allocated to other critical tasks. This can be accomplished using the processor affinity mask (see Chapter 9) in a job object.

Job objects are described in a later section. Finally, it is possible to create independent threads within a process, and these threads will also be scheduled on separate SMP processors. Chapter 7 describes threads and performance issues related to their use. Process Execution Times You can determine the amount of time that a process requires (elapsed, kernel, function, which is not available on and user times) using the Windows 9x. ; )e li Fp me T. ] co rP i[ e li F co rP ( el iF e te le D ; )] co rP i[ c o rP h( e ld na H es ol C se miTs seco rPte G

MP 64:2 4002 ,82 rebmetpeS , yadseuT 281 e gaP mf. 60hc_traH 182 CHAPTER 6 PROCESS MANAGEM ENT ; 0 n ru te r ; )c or Ph ( e er f 😉 el iF co rP ( e er f } } The process handle can refer to a process that is still running or to one that has terminated. Elapsed time can be computed by subtracting the creation time type is a 64-bit from the exit time, as shown in the next example. The to perform the subtraction. The item; create a union with a example in Chapter 3 showed how to convert and display file times. is similar and requires a thread handle for a parameter.

Chapter 7 covers thread management. Example: Process Execution Times The next example (Program 6–2) is a command called (time print) that is command ( is supported by the command prompt, similar to the UNIX so a different name is required). Elapsed, kernel, and system times can be printed, although only elapsed time is available on Windows 9x. One use for this command is to compare the execution times and efficiencies of the various file copy and ASCII to Unicode functions implemented in previous chapters. , a Windows function that returns the This program uses strings. omplete command line as a single string rather than individual , to scan the command line The program also uses a utility function, listing is in Appendix A. and skip past the executable name. The function to determine the OS version. Program 6–2 uses the With Windows 9x and CE, only the elapsed time is available. The code for these systems is shown to illustrate that a program can, in some cases, be made to operate, at least partially, on a range of Windows versions. { )] [ vg ra RT ST PL , cg r a tn i( n ia m t_ t ni ” h. g nh Ty rv E” e d ul cn i# /* . p em it . 6 r et pa hC */ pemit Program 6–2 Process Times Wsl v gra EM ITELI F p emi t xE no isr eVt eG grApikS gr ApikS )emiTresUpl EMITELIFPL ,emiTlenreKpl EMITELIFPL ,emiTtixEpl EMITELIFPL , emiTnoitaerCpl EMITELIFPL ,ssec orPh ELDNAH ( semiTssec orPteG LOOB RE GETNI_EGRA L emit en i Ld n a mm o Ct e G MP 64:2 4002 ,82 rebmetpeS , yadseuT 381 e gaP mf. 60hc_traH EXAMPLE: PROCESS EXECUTION TIMES 183 emit s e mi T d a er h T te G .. . /* . y ln o em it d e sp al E . E C d na x 9 sw od n iW * / { e sl e } 😉 sd no c es il li Mw . s y Si Te K , dn oc eS w. s yS iT eK , et u ni Mw . s yS iT e K ,r uo Hw . y Si Te K ,) “n d 30 %: d 20 %: d2 0% :d 2 0% : em iT s y S” ( T_ ( ft n ir pt _ 😉 sd no c es il li Mw . s y Si Ts U , dn oc eS w. s yS iT sU , et u ni Mw . s yS iT s U ,r uo Hw . s y Si Ts U , )” n d3 0% :d 2 0% :d 20 %: d2 0 % :e mi T re s U” ( T_ ( ft n ir pt _ 😉 sd no c es il li Mw . s y Si Tl E , dn oc eS w. s yS iT lE , et u ni Mw . s yS iT l E ,r uo Hw . s y Si Tl E , )” n d3 0% :d 2 0% :d 20 %: d2 0 % :e mi T la e R” ( T_ ( ft n ir pt _ 😉 sy S iT sU & ,e mi T re sU &( e mi T me ts yS oT em i Te li F 😉 sy Si T eK & ,e mi Tl e nr eK &( e mi T me ts yS oT em i Te li F 😉 sy Si Tl E& ,t f. m iT de s pa lE &( e mi T me ts yS oT em i Te li F ;i l. em i Te ta er C – i l. em iT ti xE = il . e mi Td e sp al E 😉 em iT re sU & , em iT le nr e K& , tf . e mi T ti xE & , tf . e mi Te ta e rC & ,c or Ph ( s em iT ss ec o rP te G /* . s em it r es U & , le nr eK , d es pa lE . TN W */ { ) TN s I( f i ; ) sy Se mi Tt ix E &( e mi Tm et s yS te G 😉 ET IN IF NI ,c or Ph ( tc e jb Oe lg ni Sr o Ft ia W 😉 0 ,E SL AF , E ZI NO RH CN YS | NO IT AM RO F NI _Y RE UQ _S S EC OR P , c or Ph & ,) ( s se co rP tn er r uC te G , ss ec o rP h. f nI co r P ,) ( ss ec or P tn er ru Ct eG ( e ld na He ta c il pu D /* . ss e co rp e ht o t s se cc a DE RI U QE R ll a ev a h ew t ah t e ru ss A * / 😉 of n Ic or P& , pU tr a tS & ,L LU N , LL UN , SS AL C _Y TI RO IR P_ L AM RO N ,E UR T , LL UN , LL UN ,v gr at , LL U N( s se co rP e ta er C /* . et e lp mo c ot s se c or p ro f ti a w ;e ni l dn a mm oc e ht e t uc ex E * / 😉 s yS em iT tr at S &( e mi Tm et s yS te G ; )p Ut ra tS & ( of nI pu tr a tS te G /* . T N_ 23 NI W_ M RO FT AL P_ RE V s nr ut er ) sn o is re v ll a( TN * / ; ) TN _2 3N IW _M R OF TA LP _R EV = = d Im ro ft al P wd . eV SO ( = T Ns I ; )r eV S O& ( xE no is r eV te G ; )O FN IN OI S RE VS O( fo ez is = ez iS of nI n oi sr eV SO wd . re VS O ; co rP h E LD NA H ;T Ns I L OO B ; re V SO O FN IN OI S RE VS O 😉 ) ( en iL dn am mo C te G( g rA pi k S = vg ra t R TS TP L ; s yS em iT ti xE ,s yS em iT tr a tS , sy Si Ts U , sy Si Te K ,s y Si Tl E EM IT M ET SY S ;e m iT re sU , em i Tl en re K EM I TE LI F ;e mi Td es p al E ,e mi Tt i xE , em iT et a er C } ;t f EM I TE LI F ;i l GN O LG NO L /* . ci t em ht ir a em i t el if r of d e ri uq er e ru t cu rt S */ { no in u ; o fn Ic or P NO I TA MR OF NI _S S EC OR P ; pU t ra tS O FN IP U TR AT S

MP 64:2 4002 ,82 rebmetpeS , yadseuT 481 e gaP mf. 60hc_traH 184 CHAPTER 6 PROCESS MANAGEM ENT can now be used to compare the various ASCII to Unicode file copy and (Program 2-4) and (Program 5–5). Appendix sorting utilities such as C summarizes and briefly analyzes some results. (Program 6–1) gives kernel Notice that measuring a program such as and user times only for the parent process. Job objects, described near the end of this chapter, allow you to collect information on a group of processes.

Appendix C shows that, on an SMP system, performance can improve as the separate processes, or more accurately, threads, run on different processors. There can also be performance gains if the files are on different physical drives. Generating Console Control Events Terminating a process can cause problems because the terminated process cannot clean up. SEH does not help because there is no general method for one process to cause an exception in another. 1 Console control events, however, allow one process to send a console control signal, or event, to another process in certain limited circumstances.

Program 4–5 illustrated how a process can set up a handler to catch such a signal, and the handler could generate an exception. In that example, the user generated a signal from the user interface. It is possible, then, for a process to generate a signal event in another specified creation flag value, process or set of processes. Recall the . If this flag is set, the new process ID identifies a group of processes, and the new process is the root of the group. All new processes call created by the parent are in this new group until another flag.

The grouped processes are similar to uses the UNIX process groups. or in a speciOne process can generate a fied process group, identifying the group with the root process ID. The target processes must have the same console as that of the process generating the event. In 1 Chapter 10 shows an indirect way for one thread to cause an exception in another thread, and the same technique can be used between threads in different processes. s se c or P et ae r C TNEV E_KAERB_LRTC s s e c o r P et a e r C MMtros PMperg TNEVE_C_LRTC PUORG _SSECORP_WEN_ET AERC PU ORG _SSE CORP _WEN _ETA ERC uota pemit Using the e mi t ;0 nr ut er 😉 c or Ph ( el dn a He so lC 😉 s se co rP h. of n Ic or P( e ld n aH es ol C 😉 d ae rh Th . o fn I co rP ( el dn a He so lC } MP 64:2 4002 ,82 rebmetpeS , yadseuT 581 e gaP mf. 60hc_traH GENERATING CONSOLE CONTROL EVENTS 185 } Command Example: Simple Job Management UNIX shells provide commands to execute processes in the background and to obtain their current status. This section develops a simple “job shell” with a similar set of commands. The commands are as follows. It is straightforward to create additional commands for suspending existing jobs or moving them to the foreground.

Because the shell, which maintains the job list, may terminate, the shell employs a user-specific shared file to contain the process IDs, the command, and related information. In this way, the shell can restart and the job list will still be intact. Furthermore, several shells can run concurrently. An exercise places this information in the registry, rather than in a temporary file. Concurrency issues will arise. Several processes, running from separate command prompts, might perform job control simultaneously. The job management ssecorPetan imreT llik • sboj • ists the current active jobs, giving the job numbers and process IDs. This is similar to the UNIX command of the same name. terminates a job. This implementation uses the function, which, as previously stated, does not provide a clean shutdown. There is also an option to send a console control signal. & gbboj g bboj • uses the remaining part of the command line as the command line for a command returns immediately rather than new process, or job, but the waiting for the new process to complete. The new process is optionally given its own console, or is detached, so that it has no console at all.

This approach is similar to running a UNIX command with the option at the end. TN EVE _C _LR TC The f irst pa rame ter, then, m ust be one o f either . The second parameter identifies the process group. )puorGssec orPwd DROWD ,tnevEl rtCwd DROWD ( tnev ElrtCelosnoCet areneG LOOB SSECORP_ DEHCATED MP 64:2 4002 ,82 rebmetpeS , yadseuT 681 e gaP mf. 60hc_traH 186 CHAPTER 6 PROCESS MANAGEM ENT particular, the calling process cannot be created with its own console (using the or flag). ELOSNOC_WEN_ET AERC TNEVE_KAERB_ LRTC or ; )] 0[ rt sg ra ( re w oL ra hC /* .

A x id ne pp A ee S * / 😉 sg rA p , cg rA co L& ,d na mm oC ( s gr At eG / * . bo j we n ro f e ni l dn am m oc n ia tb o o t tu pn i eh t e sr aP */ ;’ 0 ‘ = c p* 😉 ‘n ‘ , dn a mm oC ( rh cr t s = cp ; )n i dt s ,E NI L_ D NA MM OC _X AM ,d na mm oC ( s tt eg f_ 😉 )” $ MJ “( T _ ,) ” s% “( T _( f t ni rp t_ { )t ix E! ( e li hw ; )) ” n tn em eg an a M bo J sw od n iW “( T _( f t ni rp t_ / * . t i e tu ce xe d n a ,d na mm oc da er , re su tp mo rP */ ;] i [ rt sg ra = ]i [ sg rA p ) ++ i ;G RA _X A M < i ;0 = i( r of ; ]G RA _ XA M[ s gr Ap RT ST PL ;] E NI L_ DN AM MO C _X AM [ ]G RA _ XA M[ r ts gr a R AH CT /* . g r a la co L */ ;c gr Ac oL , i D RO WD ; cp * , ]0 1 + EN I L_ DN AM MO C_ X AM [ dn am mo C R AH CT ; ES LA F = ti x E LO OB { )] [ vg ra RT ST PL , cg r a tn i( n ia m t_ t ni ” h . t gM bo J” e d ul cn i# ” h. g nh Ty rv E” e d ul cn i# /* . la ng i s lo rt no c e lo sn oc a e t ar en eg o t n oi tp o na s i e re hT . y li ma f b oj f o bo j d ei fi ce ps a et an im re T – – ll ik . s bo j d nu or gk ca b l la t si L – – sb oj . d nu or gk c ab e ht n i b oj a n uR – – g bb oj : sd na mm oc tn em eg an am bo j — c . l eh Sb oJ */ /* . 6 r et pa hC */ MP 64:2 4002 ,82 rebmetpeS , yadseuT 781 e gaP mf. 60hc_traH Program 6–3 :llehSboJ Program 6–3 is the job shell that prompts the user for one of three commands and then carries out the command. This program uses a collection of job management functions, which are shown in Programs 6–4, 6–5, and 6–6. Creating a Background Job functions use file locking (Chapter 3) on the job list file so that a user can invoke job management from separate shells or processes.

The full program on the book’s Web site has a number of additional features, not shown in the listings, such as the ability to take command input from a file. will be the basis for a more general “service shell” in Chapter 13 (Program 13–3). Windows NT services are background processes, usually servers, that can be controlled with start, stop, pause, and other commands. Create, List, and Kill Background Jobs EXAMPLE: SIMPLE JOB MANAGEMENT l le hS b oJ 187 😉 3 , ss ec or Ph . o f nI ss ec or P( ss ec or Pe ta n im re T { e sl e ; )d ae rh T h. f nI ss ec o rP ( da er hT e mu se R ) 0 => o Nb o J( f i / * ” h. tg Mb oJ ” e eS * / 😉 v gr at , of nI ss e co rP &( r eb m uN bo Jt eG = oN bo J / * “. es ab a t ad ” bo j eh t o tn i e ld n ah d na D I ss e co rp e ht r e tn e dn a re b mu n bo j a e ta er C * / 😉 of nI ss e co rP & ,p Ut r at S& , LL UN ,L LU N ,P U OR G_ SS EC OR P_ W EN _E TA ER C | D ED NE PS US _ ET AE RC | e t ae rC f ,E UR T , LL UN , LL UN ,v gr at , LL U N( s se co rP e ta er C /* . d er et ne b oj e c no e mu se R . de dn ep su s d ae rh t/ bo j e ta er C * / ; 0 : S SE CO RP _D EH C AT ED ? 1[ sg al F : EL OS NO C_ WE N_ E TA ER C ? ]0 [ s ga lF = e t ae rC f 😉 vg ra t( gr Ap ik S = vg r at ) ‘- ‘ == ]0 [ ]1 [ vg r a( f i / * . s ts ix e ti fi , ll ew s a d le if n oi t po e ht r ev o p ik S * / 😉 LL UN , ]1 [ s ga lF & ,] 0 [ sg al F& , )” d c” ( T_ , vg r a ,c gr a( s n oi tp O ; )p Ut ra tS & ( of nI pu tr a tS te G ; )d na m mo C( g rA pi k S = vg ra t R TS TP L ;o fn I ss ec or P NO I TA MR OF NI _S S EC OR P ; pU t ra tS O FN IP U TR AT S ; ]2 [ sg al F L OO B ; oN bo J G NO L ;e ta er Cf DR OW D { ) dn am mo C RT S TP L ,] [ vg ra RT ST PL , cg r a tn i( g bb o J tn i /* . b bo j h ti w el os no c s er ah s ss e co rp e ht , t es s i re ht i en f I . e lo sn oc o n h ti w ,d eh c at ed s i ss e co rp w en e h T :d . el os no c a s se co rp we n eh t ev i G :c ] ev is ul cx e y ll au tu m e ra s no it pO [ e ni l- dn am mo c ] sn oi tp o[ gb bo j * / ; 0 n ru te r } } ; )) “n
ia ga y r T . na mm oc la ge ll I” ( T _( f tn ir pt _ e sl e } ;E UR T = t ix E { ) 0 == ) )” t iu q” ( T_ , ] 0[ r ts gr a( pm cs ct _( f i e sl e } ; )d n am mo C ,s gr A p ,c gr Ac oL ( l li K { ) 0 == ) )” l li k” ( T_ , ] 0[ r ts gr a( pm cs ct _( f i e sl e } ; )d n am mo C ,s gr A p ,c gr Ac oL ( s bo J { ) 0 == ) )” s bo j” ( T_ , ] 0[ r ts gr a( pm cs ct _( f i e sl e } 😉 dn a mm oC , sg rA p , cg rA co L( gb bo J { ) 0 == )) “g bb oj “( T_ , ]0 [ rt s gr a( p mc sc t _( f i MP 64:2 4002 ,82 rebmetpeS , yadseuT 881 e gaP mf. 60hc_traH 188 CHAPTER 6 PROCESS MANAGEM ENT 0 nr ut er 😉 r eb mu Nb oJ , ) “n uo d em i t ro d et an i mr et ] d% [ b oJ “( T _( f t ni rp t_ ; )s se c or Ph ( el dn a He so lC 😉 00 05 , s se co rP h( t c ej bO el gn iS r oF ti aW 😉 E DO C_ TI XE _M J , ss ec or Ph ( s se co rP et a ni mr eT es le ; )d Is se co rP ,T NE VE _C _L R TC ( tn ev El r tC el os no Ce t ar en eG ) Cl rt nC ( f i es le 😉 dI s se co rP , TN E VE _K AE RB _L R TC ( tn ev El r tC el os no Ce t ar en eG )B lr t nC ( fi } ;2 nr ut er 😉 ES LA F ,0 ,) “n . de ta n im re t yd ae r la s se co rP ” ( T_ ( ro rr E tr op eR /* . s u n i eb t on y a m DI s se co r P */ { ) LL U N == s se co r Ph ( fi ; )d Is se co rP ,E SL AF , SS E CC A_ LL A_ SS E CO RP ( ss ec o rP ne pO = s s ec or Ph / * . t mg m b oj e eS * / ; )r eb mu Nb o J( d Is se co r Pd ni F = dI s se co rP ; )] oN b oJ i[ v gr a( io tt _ = re b mu Nb oJ /* . bo j s ih t ht iw d e ta ic os sa D I s se co rp e h t dn iF */ ; )L LU N , Cl rt nC & , Bl rt nC & ,) ” cb “( T _ ,v g ra , cg ra ( s no it pO = oN bo Ji } ;d el li K ,B l rt nC , Cl rt n C LO OB ; ss ec or Ph EL DN AH ;o Nb oJ i , re bm uN bo J , dI ss ec or P D RO WD { ) dn am mo C RT S TP L ,] [ vg r a RT ST PL , c gr a tn i( l l iK t ni / * . se c or p eh t et a ni mr et , es i wr eh tO C- l rt C a et ar e ne G cka er B- l rt C a et ar e ne G bre bm uN b oJ ] sn oi tp o [ ll ik */ } ;0 nr ut er / * . s no it c nu f tm gm b o j ee S */ ; 1 n ru te r )) ( s bo Jy al ps i D! ( fi { ) dn am mo C RT S TP L ,] [ vg r a RT ST PL , c gr a tn i( s b oJ t ni /* . s bo j de pp o ts r o gn in n ur l la t si L : sb oj */ ;0 nr ut er 😉 dI ss ec or P wd . o fn Is se c or P ,o Nb oJ ,) “n d % ]d % [ “( T _( f t ni rp t_ 😉 ss ec o rP h. of nI ss e co rP ( el dn a He so lC ; )d ae r hT h. of nI ss e co rP ( el dn a He so lC } } ;5 nr ut er 😉 ES LA F , 0 ,) “. s il bo j ni m oo r o N :r or rE ” ( T_ ( ro rr E tr op eR 😉 ss ec o rP h. of nI ss e co rP ( el dn a He so lC EXAMPLE: SIMPLE JOB MANAGEMENT 189 MP 64:2 4002 ,82 rebmetpeS , yadseuT 981 e gaP mf. 60hc_traH ; 1- n ru t er ) EU LA V_ EL D NA H_ DI LA VN I = = at aD bo J h( f i ; )L LU N ,L A MR ON _E TU BI R TT A_ EL IF , S YA WL A_ NE PO ,L LU N , ET IR W_ E RA HS _E LI F | D AE R_ ER AH S _E LI F , E TI RW _C IR EN E G | DA ER _C I RE NE G ,e ma Ne li Ft g Mb oJ ( el iF e ta er C = at a Db oJ h /* ” tg M bo J. em aN re s U pm t ” se c ud or P * / ;1 – nr ut er )) em aN el iF tg M bo J( e ma Ne l iF tg Mb oJ te G ! f i ;t ra tS n oi ge R DE PP A LR EV O ;] HT A P_ XA M[ e ma N el iF tg Mb oJ RA HC T ; hg iH sF , wo L sF , ed oC ti xE ,r ef Xn , 0 = r eb mu Nb oJ DR OW D ; dr oc eR bo J B OJ _M J ; ss ec or Ph ,a ta Db oJ h E LD NA H { / * . es ab at ad bo j eh t ot ni no it am ro fn i s se co rp w e n eh t r et ne d na ,s se co rp w en eh t ro f re b mu n bo j a e ta er C * / )d na mm oC R T ST CP L , o fn Is se co rP p * NO IT AM RO FN I _S SE CO RP ( r eb mu Nb oJ te G G NO L 😉 RT S TP L( e ma Ne l iF tg Mb oJ te G d io v /* . A x id ne pp A ni d e ts iL * / “h . tg Mb oJ ” ed u lc ni # “h . n hT yr vE ” ed u lc ni # / * . n oi t cn uf y ti li t u tn em eg an a m bo J * / MP 64:2 4002 ,82 rebmetpeS , yadseuT 091 e gaP mf. 60hc_traH 190 Notice how the command creates the process in the suspended state (Program 6–4), to and then calls the job management function, get a new job number and to register the job and its associated process. If the job cannot be registered for any reason, the job’s process is terminated immediately. Normally, the job number is generated correctly, and the primary thread is resumed and allowed to run. The next three programs show three individual job management functions.

These . functions are all included in a single source file, function. Notice the use of The first, Program 6–4, shows the file locking with a completion handler to unlock the file. This technique protects against exceptions and inadvertent transfers around the unlock call. Such a transfer might be inserted accidentally during code maintenance even if the original program is correct. Also notice how the record past the end of the file is locked in the event that the file needs to be expanded with a new record. rebmu NboJte G c. tgMb oJ re b mu N bo J te G Getting a Job Number gb b o j Program 6–4

CHAPTER 6 :tg MboJ PROCESS MANAGEM ENT Creating New Job Information ; 1 + r eb mu Nb oJ nr ut er } ; )a ta D bo Jh ( el dn a He so lC ; )t ra tS n oi ge R& ,0 , BO J _M JS + w oL s F ,0 , at aD b oJ h( x Ee li F kc ol nU { yl l an if __ / * . y rt d n E */ } ; )L LU N , re fX n& , B OJ _M JS , dr o ce Rb oJ & ,a t aD bo Jh ( el i Fe ti rW 😉 H TA P_ XA M ,d n am mo C ,e ni L dn am mo C. dr o ce Rb oJ ( yp c cn sc t_ ;d Is se co r Pw d> -o fn Is s ec or Pp = d I ss ec or P. dr o ce Rb oJ 😉 T NE RR UC _E LI F , LL UN , B OJ _M JS )G NO L (- , at aD bo J h( r et ni oP e li Ft eS /* . pu k ca B . l if f o d ne t a to N * / )0 = ! re f Xn ( fi / * . e no w en a et ae rc o t d ee n dn a e li f fo dn e t a er a ew ro , dn uo f n ee b sa h to l s yt pm e na re ht iE */ } ; ++ re b mu Nb oJ ;k ae rb ) ) EV IT CA _L LI T S =! e do Ct i xE ( && )e do C ti xE & ,s se c or Ph ( ss ec o rP ed oC ti xE t eG ( fi ;k ae rb ) LL U N == s se co r Ph ( fi 😉 dI ss ec or P . d ro ce Rb oJ ,E SL AF ,S S EC CA _L LA _S S EC OR P( ss ec o rP ne pO = s s ec or Ph ; ka er b ) 0 == d Is se c or P. dr oc eR b oJ ( fi { )) 0 > re f Xn ( && )L LU N ,r ef X n& , BO J_ MJ S , dr oc eR bo J & ,a ta Db oJ h ( el iF da eR ( e li hw /* . o l s yt pm e dn i f ot s dr oc e r da eR */ { y rt __ 😉 tr at Sn o ig eR & ,0 , B OJ _M JS + w o Ls F ,0 ,K CO L_ E VI SU LC XE _E L IF KC OL , at a Db oJ h( x Ee l iF kc oL ; )h gi Hs F& , a ta Db oJ h( e z iS el iF te G = w oL sF ;0 ) EL DN AH ( = t ne vE h. tr at S no ig eR ; 0 = hg iH t es ff O. tr at S no ig eR ; 0 = t es ff O. tr at S no ig eR /* . s se cc a ev i su lc xe r of dr oc er we n e lb is so p e no s ul p el i f er it ne e h t kc oL */ MP 64:2 4002 ,82 rebmetpeS , yadseuT 191 e gaP mf. 60hc_traH Program 6–5 shows the } sboJyalps iD Listing Background Jobs EXAMPLE: SIMPLE JOB MANAGEMENT job management function. 191 0 = dI s se co rP . d ro c eR bo J ; )T N ER RU C_ EL IF ,L LU N , re fX n) GN OL ( – ,a ta Db oJ h ( re tn io Pe l iF te S /* . dr oc er en o pu k ca B * / { )L LU N = = ss ec or P h( f i /* . me ts ys ni r eg no l o n er a ta ht se ss ec or p e vo me R * / 😉 en iL dn a mm oC . d ro ce R bo J ,) “n s % ” ( T_ ( ft n ir pt _ 😉 )” ” ( T _( f tn ir pt _ e sl e 😉 )” en oD +” ( T_ ( ft n ir pt _ )E VI TC A _L LI TS = ! e do Ct ix E( f i e sl e ; )) “e no D ” ( T_ ( ft n ir pt _ )L LU N = = ss ec or P h( f i 😉 re bm uN b oJ , )” ] d% [ ” ( T_ ( ft n ir pt _ 😉 e do Ct ix E& , s se co rP h( s s ec or Pe do Ct i xE te G )L LU N = ! s ec or P h( f i 😉 dI s se co rP . d ro c eR bo J , ES LA F ,S SE C CA _L LA _S SE C OR P( s se co r Pn ep O = ss e co rP h ; eu n it no c ) 0 = = dI ss ec o rP . d ro ce Rb o J( f i ;+ +r eb m uN bo J {) )0 > r ef X n( & & ) LL UN , re f Xn & ,B OJ _M J S ,d ro ce Rb oJ & , at aD bo Jh ( e li Fd ae R( el ih w { yr t_ _ 😉 tr a tS no ig eR & , hg iH sF , wo L sF , 0 , KC OL _ EV IS UL CX E_ EL I FK CO L ,a ta D bo Jh ( xE el i Fk co L 😉 hg iH sF & ,a t aD bo Jh ( ez i Se li Ft eG = wo Ls F ; 0) E LD NA H( = t n ev Eh . t ra tS n oi ge R ;0 = h gi Ht e sf fO . ra tS n oi ge R ;0 = t e sf fO . t ra tS n oi ge R ; )L LU N ,L AM R ON _E TU BI RT T A_ EL IF , GN I TS IX E_ NE PO ,L LU N , ET IR W_ E RA HS _E LI F | D AE R_ ER AH S _E LI F , E TI RW _C IR EN E G | DA ER _C I RE NE G ,e ma Ne li Ft g Mb oJ ( el iF e ta er C = at a Db oJ h ; )e ma Ne l iF tg Mb oJ ( e ma Ne li Ft gM b oJ te G ;t ra tS n oi ge R DE PP A LR EV O ;] HT A P_ XA M[ e ma N el iF tg Mb oJ RA HC T ; hg iH sF , wo L sF , ed oC ti xE ,r ef Xn , 0 = r eb mu Nb oJ DR OW D ; dr oc eR bo J B OJ _M J ; ss ec or Ph ,a ta Db oJ h E LD NA H { / * . ut at s b oj g ni tr op er ,e li f es ab a ta d bo j eh t n ac S * / )d io v( sb oJ ya lp si D L OO B MP 64:2 4002 ,82 rebmetpeS , yadseuT 291 e gaP mf. 60hc_traH 192 Program 6–5 CHAPTER 6 :tg MboJ PROCESS MANAGEM ENT Displaying Active Jobs /* . dr oc er eh t da er d n a kc oL */ ; )N IG EB _E LI F , LL UN , ) 1 – re bm uN b oJ ( * BO J_ M JS , at aD bo J h( r et ni oP e li Ft eS /* . e gn ar n i si re bm uN bo J t ah t se ru ss a m ar go rp l l uf e hT * . e bm un b oj de if ic ep s e ht r of y rt n e eh t ot n o it is oP */ ; 0 nr ut e r )E UL AV _E L DN AH _D IL AV N I == a ta Db o Jh ( fi 😉 LL UN , LA M RO N_ ET UB IR T TA _E LI F ,G N IT SI XE _N EP O , LL UN ,E TI RW _ ER AH S_ EL IF | DA ER _E RA H S_ EL IF , D AE R_ CI RE NE G , em aN el iF t gM bo J( e li F et ae rC = a t aD bo Jh 😉 em aN e li Ft gM bo J( em aN el iF tg M bo Jt eG / * . el if t ne me g an am b oj e h t ne pO */ ; tr at S no ig eR D