Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17


Regarding the processes and Win32 API

Posted on 2004-08-13
Medium Priority
Last Modified: 2010-04-15

  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;

Question by:pascal_lalonde
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2

Author Comment

ID: 11795835
 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!
LVL 86

Expert Comment

ID: 11796063
>>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.

Author Comment

ID: 11797230

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 ...
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

LVL 86

Accepted Solution

jkr earned 375 total points
ID: 11797394
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.

Author Comment

ID: 11804210
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 ?


Author Comment

ID: 11821462
   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!

Featured Post


Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode ( They will have you believe that Unicode requires you to use…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.

721 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question