• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 320
  • Last Modified:

Regarding the processes and Win32 API


  In the code that follows, there is the instruction:

dwProcNb = WaitForMultipleObjects (argc - 2 - dwNbOptions,
                                                      hProc, FALSE, INFINITE);

  When I execute this console application, the printf that follows this instruction is always:

Process with index 0 terminated.
Process with index 0 terminated.
Process with index 0 terminated.
Process with index 0 terminated.

Note that there were 4 grep processes. Why the index is always 0? I expected indexes 0, 1, 2, 3 but not necessarily in this order.

+++++++++++++++++ the code ++++++++++++++++++++

#include "EvryThng.h"

int _tmain (int argc, LPTSTR argv [])

/* Create a separate process to search each file on the
    command line. Each process is given a temporary file,
    in the current directory, to receive the results. */
    LPHANDLE lphTempFile;
    SECURITY_ATTRIBUTES StdOutSA = /* SA for inheritable  
                                                              handle. */
    TCHAR CommandLine [MAX_PATH + 100];
    STARTUPINFO StartUpSearch, StartUp;
    int iProc;
    HANDLE *hProc;  /* Pointer to an array of proc handles. */
    typedef struct {TCHAR TempFile [MAX_PATH];} PROCFILE;
    PROCFILE *ProcFile; /* Pointer to array of temp file
                                       names. */
    DWORD dwOptions =0;
    DWORD dwProcNb;
    int dwNbOptions =0;
    BOOL Flags[2];

    if (argc < 3)
        ReportError (_T ("Usage: grepMP pattern files."), 1,  

    /* Startup info for each child search process as well as
        the child process that will display the results. */

    GetStartupInfo (&StartUpSearch);
    GetStartupInfo (&StartUp);

    dwOptions = Options(argc, argv, _T ("cd"), &Flags[0],
                              &Flags[1], NULL);
    dwNbOptions = (int)dwOptions - 1;
     /* Allocate storage for an array of process data structures,
         each containing a process handle and a temporary file
         name. */

     ProcFile = malloc ((argc - 2 - dwNbOptions) * sizeof  
     hProc = malloc ((argc - 2 - dwNbOptions) * sizeof
     lphTempFile = malloc ((argc - 2 - dwNbOptions) * sizeof

     /* Create a separate "grep" process for each file on the
         command line. Each process also gets a temporary file
         name for the results; the handle is communicated
         through the STARTUPINFO structure. argv [1] is the
         search pattern. */

    for (iProc = 0; iProc < argc - 2 - dwNbOptions; iProc++) {

        /* Create a command line of the form: grep argv [1]
            argv [iProc + 2] */
        _stprintf (CommandLine, _T ("%s%s%s%s"),
                    _T ("grep "),
                                               argv [1+dwNbOptions],
                                               _T (" "),
                  argv [iProc + dwNbOptions + 2]);

        /* Create the temp file name for std output. */

        if (GetTempFileName (_T ("."), _T ("gtm"), 0,
                           ProcFile [iProc].TempFile) == 0)
          ReportError (_T ("Temp file failure."), 2, TRUE);

        /* Set the std output for the search process. */

        lphTempFile[iProc] = /* This handle is inheritable */
        CreateFile (ProcFile [iProc].TempFile,
                     GENERIC_READ | GENERIC_WRITE,
                    FILE_FLAG_DELETE_ON_CLOSE, NULL);
        if (lphTempFile[iProc] == INVALID_HANDLE_VALUE)
            ReportError (_T ("Failure opening temp file."), 3,  

        /* Specify that the new process takes its std output
            from the temporary file's handles.
            You must set the std output handle as well; it
            is not inherited from the parent once the
            dwFlags member is set to STARTF_USESTDHANDLES.
            The std input handle would also be set here if
            the child processes did not take their std in
            from the command line. */

        StartUpSearch.dwFlags = STARTF_USESTDHANDLES;
        StartUpSearch.hStdOutput = lphTempFile[iProc];
        StartUpSearch.hStdError = GetStdHandle

        /* Create a process to execute the command line. */

        if (!CreateProcess (NULL, CommandLine, NULL, NULL,
                 TRUE, 0, NULL, NULL, &StartUpSearch,
            ReportError (_T ("ProcCreate failed."), 4, TRUE);

       CloseHandle (ProcessInfo.hThread);

        /* Save the process handle. */
        hProc [iProc] = ProcessInfo.hProcess;

    }/*End of for loop*/

    /* Processes are all running. Wait for them to complete,
        then output the results - in the order of the command
        line file names. */
    for (iProc = 0; iProc < argc - 2 - dwNbOptions; iProc++) {
        dwProcNb = WaitForMultipleObjects (argc - 2 -  
                               hProc, FALSE,
        dwProcNb -= WAIT_OBJECT_0;
        printf("Process with index %u terminated.\n",
    }/*End of 2nd for loop*/

    for (iProc = 0; iProc < argc - 2 - dwNbOptions; iProc++)
        CloseHandle (hProc [iProc]);

    /* Result files sent to std output using "cat".
        Delete each temporary file upon completion. */

    for (iProc = 0; iProc < argc - 2 - dwNbOptions; iProc++) {
        if (GetCompressedFileSize (ProcFile [iProc].TempFile,
            NULL) > 2) {
            if (argc > 3) {
      /* Display file name if more than one. */
      _ftprintf (stdout, _T ("%s:\n"),                                      argv [iProc + 2 +  
      fflush (stdout);
           _stprintf (CommandLine, _T ("%s%s"),
               _T ("cat "),
                         ProcFile [iProc].TempFile);
           if (!CreateProcess (NULL, CommandLine, NULL, NULL,
                             TRUE, 0, NULL, NULL, &StartUp,
               ReportError (_T ("Failure executing cat."), 5, TRUE);
           WaitForSingleObject (ProcessInfo.hProcess, INFINITE);
           CloseHandle (ProcessInfo.hThread);
           CloseHandle (ProcessInfo.hProcess);
           CloseHandle (lphTempFile[iProc]);
    free (ProcFile);
    free (hProc);
    return 0;

  • 4
  • 2
1 Solution
pascal_lalondeAuthor Commented:
 It is the code of a command called grepMP.
This command is used to search a pattern in one or more text files. It creates as many child processes as the number of text files. So the search is accompished in parallel in all the text files.

  The format of the command is:

  grepMP <optional switches>  <pattern(obligatory)>
              file1.txt   file2.txt

  Thank you!
>>Why the index is always 0?

Because you are waiting 4 times and the wait command always returns because your first entry in the handle array already has reached the 'terminated' state.
pascal_lalondeAuthor Commented:

But when I enter the following command line:

  grepMP electronic  test.txt  testshort.txt

  ,where the file testshort.txt has few lines (around 10)
and test.txt is 26 MB long.

I obtain on the screen:

  Process with index 1 terminated.
  Process with index 1 terminated.

I would rather expect something like:

  Process with index 1 terminated.
  Process with index 0 terminated.

I am confused ...
Protect Your Employees from Wi-Fi Threats

As Wi-Fi growth and popularity continues to climb, not everyone understands the risks that come with connecting to public Wi-Fi or even offering Wi-Fi to employees, visitors and guests. Download the resource kit to make sure your safe wherever business takes you!

That's the same effect. Either wait for all processes to finish or make that read

int nRunning = argc - 2 - dwNbOptions;
int nTotal = nRunning;
HANDLE hTable  = (HANDLE) malloc ( nRunning * sizeof (HANDLE));
memcpy(hTable, hProc, nRunning * sizeof (HANDLE));

    for (iProc = 0; iProc < argc - 2 - dwNbOptions; iProc++) {
       HANDLE hRunning = (HANDLE) malloc ( nRunning * sizeof (HANDLE));
       for ( int i = 0; i < nTotal; n++) {

           if ( hTable[i] != NULL) hRunning[i] = hTable[i};
       dwProcNb = WaitForMultipleObjects (nRunning,
                           hRunning, FALSE,
       dwProcNb -= WAIT_OBJECT_0;
       printf("Process with index %u terminated.\n",
       hTable[i] = NULL;
   }/*End of 2nd for loop*/

to re-write the array every time a process has finished.
pascal_lalondeAuthor Commented:
JKR, I am trying to understand your second answer.

In the inner for loop, the stop condition is i< nTotal but nTotal is never modified. Was your intent to write i < nRunning ?

pascal_lalondeAuthor Commented:
   Your answer helped me a lot  me but I needed to read your code many times because there a lot of bugs. Anyway, without your intervention, I would have been in a more bad situation. Thank you JKR!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Improve Your Query Performance Tuning

In this FREE six-day email course, you'll learn from Janis Griffin, Database Performance Evangelist. She'll teach 12 steps that you can use to optimize your queries as much as possible and see measurable results in your work. Get started today!

  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now