Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 315
  • Last Modified:

Regarding the processes and Win32 API

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
pascal_lalonde
Asked:
pascal_lalonde
  • 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!
0
 
jkrCommented:
>>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
 
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 ...
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
jkrCommented:
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
 
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 ?

0
 
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!
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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