View Single Post
Join Date: Oct 2007
Posts: 1,951
Reputation: Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of 
Solved Threads: 214
Featured Poster
Duoas's Avatar
Duoas Duoas is offline Offline
Posting Virtuoso

Re: damages when executing console from MFC

 
0
  #7
Jul 4th, 2008
Ah, I think I know what is happening.

The file stream is not required to keep the actual disk file up-to-date with the fstream's state at all times. It can wait until it is convenient to write data to the file.

So it looks to me like there is a race condition occurring between the two applications to access the file data.

You can force it to synchronize the disk file and the fstream's data buffer by using the flush function/manipulator, and for FILE*s use fflush().

So, when the button is clicked, the following should happen:
  1. Make sure to fflush before calling ShellExecute().
  2. Remember that ShellExecute starts the indicated process but does not wait for it to terminate. You must use one of the wait functions to wait for the program to terminate. For example:
    1. bool ExecTheChildProc()
    2. {
    3. // Both files should be flushed or closed before calling this function
    4.  
    5. // Execute the child process...
    6. HINSTANCE hChild = ShellExecute( ... );
    7.  
    8. // ...and wait for it to terminate
    9. // (You can specify a specific number of milliseconds to wait
    10. // before returning so that you can get control back periodically
    11. // and make sure your application doesn't freeze.)
    12. DWORD result;
    13. while (true) switch (WaitForSingleObject( hChild, 500 ))
    14. {
    15. case WAIT_OBJECT_0:
    16. // Success. The child is terminated
    17. // and the files are ready to be read.
    18. return true;
    19.  
    20. case WAIT_TIMEOUT:
    21. // Half a second has passed.
    22. // Make sure the application stays responsive.
    23. ProcessMessages();
    24. break;
    25.  
    26. default:
    27. // Something has gone wrong.
    28. return false;
    29. }
    30.  
    31. return false; // keep the compiler happy
    32. }
  3. Read the result.

Call the ExecTheChildProc() when the button is pressed (or put the code in your button event method).

The ProcessMessages() function is not defined by MFC. However, you can find it here.

If you don't expect the child to take much time, you can skip the loop and everything and just say:
return WaitForSingleObject( hChild, INFINITE ) == WAIT_OBJECT_0;

That's a zero on the end of the WAIT_OBJECT_0 macro.

Hope this helps.
Reply With Quote