Home > Articles > Programming > Windows Programming

This chapter is from the book

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"2 with a similar set of commands. The commands are as follows.

  • jobbg uses the remaining part of the command line as the command for a new process, or job, but the jobbg command returns immediately rather than 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. Using a new console avoids console contention with jobbg and other jobs. This approach is similar to running a UNIX command with the & option at the end.
  • jobs lists the current active jobs, giving the job numbers and process IDs. This is similar to the UNIX command of the same name.
  • kill terminates a job. This implementation uses the TerminateProcess function, which, as previously stated, does not provide a clean shutdown. There is also an option to send a console control signal.

It is straightforward to create additional commands for operations such as suspending and resuming existing jobs.

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. You could place this information in the registry rather than in a temporary file (see Exercise 6–9).

Concurrency issues will arise. Several processes, running from separate command prompts, might perform job control simultaneously. The job management functions use file locking (Chapter 3) on the job list file so that a user can invoke job management from separate shells or processes. Also, Exercise 6–8 identifies a defect caused by job id reuse and suggests a fix.

The full program in the Examples file has a number of additional features, not shown in the listings, such as the ability to take command input from a file. JobShell will be the basis for a more general "service shell" in Chapter 13 (Program 13-3). Windows services are background processes, usually servers, that can be controlled with start, stop, pause, and other commands.

Creating a Background Job

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. Run 6-6 then demonstrates how to use the JobShell system.

Program 6-4. JobMgt: Creating New Job Information

/* Job management utility function. */

#include "Everything.h"
#include "JobMgt.h" /* Listed in Appendix A. */
void GetJobMgtFileName (LPTSTR);
      LPCTSTR command)

/* Create a job number for the new process, and enter
   the new process information into the job database. */
   HANDLE hJobData, hProcess;
   JM_JOB jobRecord;
   DWORD jobNumber = 0, nXfer, exitCode, fileSizeLow, fileSizeHigh;
   TCHAR jobMgtFileName[MAX_PATH];
   OVERLAPPED regionStart;

   if (!GetJobMgtFileName (jobMgtFileName)) return -1;
                /* Produces "\tmp\UserName.JobMgt" */
   hJobData = CreateFile (jobMgtFileName,
   if (hJobData == INVALID_HANDLE_VALUE) return -1;

   /* Lock the entire file plus one possible new
      record for exclusive access. */
   regionStart.Offset = 0;
   regionStart.OffsetHigh = 0;
   regionStart.hEvent = (HANDLE)0;

   /* Find file size: GetFileSizeEx is an alternative */
   fileSizeLow = GetFileSize (hJobData, &fileSizeHigh);
          0, fileSizeLow + SJM_JOB, 0, &regionStart);

   __try {
      /* Read records to find empty slot. */
      /* See text comments and Exercise 6-8 regarding a potential
         defect (and fix) caused by process ID reuse. */
      while (ReadFile (hJobData, &jobRecord, SJM_JOB, &nXfer, NULL)
            && (nXfer > 0)) {
         if (jobRecord.ProcessId == 0) break;
         hProcess = OpenProcess(PROCESS_ALL_ACCESS,
                FALSE, jobRecord.ProcessId);
         if (hProcess == NULL) break;
         if (GetExitCodeProcess (hProcess, &exitCode)
                && (exitCode != STILL_ACTIVE)) break;

      /* Either an empty slot has been found, or we are at end
         of file and need to create a new one. */
      if (nXfer != 0) /* Not at end of file. Back up. */
         SetFilePointer (hJobData, -(LONG)SJM_JOB,
                NULL, FILE_CURRENT);
      jobRecord.ProcessId = pProcessInfo->dwProcessId;
      _tcsnccpy (jobRecord.commandLine, command, MAX_PATH);
      WriteFile (hJobData, &jobRecord, SJM_JOB, &nXfer, NULL);
   } /* End try. */

   __finally {
      UnlockFileEx (hJobData, 0, fileSizeLow + SJM_JOB, 0,
      CloseHandle (hJobData);
   return jobNumber + 1;

Program 6-5. JobMgt: Displaying Active Jobs

BOOL DisplayJobs (void)

/* Scan the job database file, reporting job status. */
   HANDLE hJobData, hProcess;
   JM_JOB jobRecord;
   DWORD jobNumber = 0, nXfer, exitCode, fileSizeLow, fileSizeHigh;
   TCHAR jobMgtFileName[MAX_PATH];
   OVERLAPPED regionStart;

   GetJobMgtFileName (jobMgtFileName);
   hJobData = CreateFile (jobMgtFileName,

   regionStart.Offset = 0;
   regionStart.OffsetHigh = 0;
   regionStart.hEvent = (HANDLE)0;

   /* Demonstration: GetFileSize instead of GetFileSizeEx */
   fileSizeLow = GetFileSize (hJobData, &fileSizeHigh);
          0, fileSizeLow, fileSizeHigh, &regionStart);

   __try {
   while (ReadFile (hJobData, &jobRecord, SJM_JOB, &nXfer, NULL)
         && (nXfer > 0)){
      if (jobRecord.ProcessId == 0)
      hProcess = OpenProcess (PROCESS_ALL_ACCESS, FALSE,
      if (hProcess != NULL)
         GetExitCodeProcess (hProcess, &exitCode);
      _tprintf (_T (" [%d] "), jobNumber);
      if (hProcess == NULL)
         _tprintf (_T (" Done"));
      else if (exitCode != STILL_ACTIVE)
         _tprintf (_T ("+ Done"));
      else _tprintf (_T (" "));
      _tprintf (_T (" %s\n"), jobRecord.commandLine);

      /* Remove processes that are no longer in system. */
      if (hProcess == NULL) { /* Back up one record. */
         SetFilePointer (hJobData, -(LONG)nXfer,
                NULL, FILE_CURRENT);
         jobRecord.ProcessId = 0;
         WriteFile (hJobData, &jobRecord, SJM_JOB, &nXfer, NULL);
   } /* End of while. */
   } /* End of __try. */

   __finally {
      UnlockFileEx (hJobData, 0, fileSizeLow, fileSizeHigh,
      CloseHandle (hJobData);

   return TRUE;

Program 6-6. JobMgt: Getting the Process ID from a Job Number

DWORD FindProcessId (DWORD jobNumber)

/* Obtain the process ID of the specified job number. */
   HANDLE hJobData;
   JM_JOB jobRecord;
   DWORD nXfer;
   TCHAR jobMgtFileName[MAX_PATH];
   OVERLAPPED regionStart;

   /* Open the job management file. */
   GetJobMgtFileName (jobMgtFileName);

   hJobData = CreateFile (jobMgtFileName, GENERIC_READ,
   if (hJobData == INVALID_HANDLE_VALUE) return 0;

   /* Position to the entry for the specified job number.
    * The full program assures that jobNumber is in range. */
   SetFilePointer (hJobData, SJM_JOB * (jobNumber - 1),
          NULL, FILE_BEGIN);

   /* Lock and read the record. */
   regionStart.Offset = SJM_JOB * (jobNumber - 1);
   regionStart.OffsetHigh = 0; /* Assume a "short" file. */
   regionStart.hEvent = (HANDLE)0;
   LockFileEx (hJobData, 0, 0, SJM_JOB, 0, &regionStart);
   ReadFile (hJobData, &jobRecord, SJM_JOB, &nXfer, NULL);
   UnlockFileEx (hJobData, 0, SJM_JOB, 0, &regionStart);
   CloseHandle (hJobData);
   return jobRecord.ProcessId;
Run 6-6

Run 6-6 JobShell: Managing Multiple Processes

Notice how the jobbg command creates the process in the suspended state and then calls the job management function, GetJobNumber (Program 6-4), to 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.

Getting a Job Number

The next three programs show three individual job management functions. These functions are all included in a single source file, JobMgt.c.

The first, Program 6-4, shows the GetJobNumber function. Notice the use of 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.

There's also a subtle defect in this function; a code comment identifies it, and Exercise 6–8 suggests a fix.

Listing Background Jobs

Program 6-5 shows the DisplayJobs job management function.

Finding a Job in the Job List File

Program 6-6 shows the final job management function, FindProcessId, which obtains the process ID of a specified job number. The process ID, in turn, can be used by the calling program to obtain a handle and other process status information.

Run 6-6 shows the job shell managing several jobs using grep, grepMP, and sortBT (Chapter 5). Notes on Run 6-6 include:

  • This run uses the same four 640MB files (l1.txt, etc.) as Run 6-1.
  • You can quit and reenter JobShell and see the same jobs.
  • A "Done" job is listed only once.
  • The grep job uses the -c option, so the results appear in a separate console (not shown in the screenshot).
  • JobShell and the grepMP job contend for the main console, so some output can overlap, although the problem does not occur in this example.

Job Objects

You can collect processes together into job objects where the processes can be controlled together, and you can specify resource limits for all the job object member processes and maintain accounting information.

The first step is to create an empty job object with CreateJobObject, which takes two arguments, a name and security attributes, and returns a job object handle. There is also an OpenJobObject function to use with a named object. CloseHandle destroys the job object.

AssignProcessToJobObject simply adds a process specified by a process handle to a job object; there are just two parameters. A process cannot be a member of more than one job, so AssignProcessToJobObject fails if the process associated with the handle is already a member of some job. A process that is added to a job inherits all the limits associated with the job and adds its accounting information to the job, such as the processor time used.

By default, a new child process created by a process in the job will also belong to the job unless the CREATE_BREAKAWAY_FROM_JOB flag is specified in the dwCreationFlags argument to CreateProcess.

Finally, you can specify control limits on the processes in a job using SetInformationJobObject.

BOOL SetInformationJobObject (
   HANDLE hJob,
   JOBOBJECTINFOCLASS JobObjectInformationClass,
   LPVOID lpJobObjectInformation,
   DWORD cbJobObjectInformationLength)
  • hJob is a handle for an existing job object.
  • JobObjectInformationClass specifies the information class for the limits you wish to set. There are five values; JobObjectBasicLimitInformation is one value and is used to specify information such as the total and perprocess time limits, working set size limits,3 limits on the number of active processes, priority, and processor affinity (the processors of a multiprocessor computer that can be used by threads in the job processes).
  • lpJobObjectInformation points to the actual information required by the preceding parameter. There is a different structure for each class.
  • JOBOBJECT_BASIC_ACCOUNTING_INFORMATION allows you to get the total time (user, kernel, and elapsed) of the processes in a job.
  • JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE will terminate all processes in the job object when you close the last handle referring to the object.
  • The last parameter is the length of the preceding structure.

QueryJobInformationObject obtains the current limits. Other information classes impose limits on the user interface, I/O completion ports (see Chapter 14), security, and job termination.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020