Solved

Regarding the processes and Win32 API

Posted on 2004-08-13
6
300 Views
Last Modified: 2010-04-15
Hello,

  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. */
    {sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
    TCHAR CommandLine [MAX_PATH + 100];
    STARTUPINFO StartUpSearch, StartUp;
    PROCESS_INFORMATION ProcessInfo;
    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,  
                           FALSE);

    /* 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  
                                (PROCFILE));
     hProc = malloc ((argc - 2 - dwNbOptions) * sizeof
                             (HANDLE));
     lphTempFile = malloc ((argc - 2 - dwNbOptions) * sizeof
                                      (HANDLE));

     /* 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_SHARE_READ | FILE_SHARE_WRITE,
                     &StdOutSA,
                    CREATE_ALWAYS,  
                    FILE_FLAG_DELETE_ON_CLOSE, NULL);
       
        if (lphTempFile[iProc] == INVALID_HANDLE_VALUE)
            ReportError (_T ("Failure opening temp file."), 3,  
                                TRUE);

        /* 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
                                             (STD_ERROR_HANDLE);

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

        if (!CreateProcess (NULL, CommandLine, NULL, NULL,
                 TRUE, 0, NULL, NULL, &StartUpSearch,
                                  &ProcessInfo))
            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 -  
                                                             dwNbOptions,
                               hProc, FALSE,
                                                             INFINITE);
        dwProcNb -= WAIT_OBJECT_0;
        printf("Process with index %u terminated.\n",
                 dwProcNb);
    }/*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 +  
                                                      dwNbOptions]);
      fflush (stdout);
            }
           _stprintf (CommandLine, _T ("%s%s"),
               _T ("cat "),
                         ProcFile [iProc].TempFile);
      
           if (!CreateProcess (NULL, CommandLine, NULL, NULL,
                             TRUE, 0, NULL, NULL, &StartUp,
                                       &ProcessInfo))
               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;
}


0
Comment
Question by:pascal_lalonde
  • 4
  • 2
6 Comments
 

Author Comment

by:pascal_lalonde
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!
0
 
LVL 86

Expert Comment

by:jkr
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.
0
 

Author Comment

by:pascal_lalonde
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 ...
0
ScreenConnect 6.0 Free Trial

Check out the updates in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI that improves session organization and overall user experience. See the enhancements for yourself!

 
LVL 86

Accepted Solution

by:
jkr earned 125 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,
                                                             INFINITE);
       dwProcNb -= WAIT_OBJECT_0;
       printf("Process with index %u terminated.\n",
                 dwProcNb);
       hTable[i] = NULL;
       --nRunning;
       free(hRunning);
   }/*End of 2nd for loop*/

to re-write the array every time a process has finished.
0
 

Author Comment

by:pascal_lalonde
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 ?

0
 

Author Comment

by:pascal_lalonde
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!
0

Featured Post

Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

Question has a verified solution.

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

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
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…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.

828 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