question

Martin C3 avatar image
1 Like"
Martin C3 asked Phil BoBo commented

How to let runprogram() wait for batch file (.bat) to finish

Hello,

I have a question about running batch files (.bat) with the runprogram() command. I call the batch file from my script, but I want the script to wait until the batch file has finished before the script executes the next command. How can I achieve this?

Example:

  1. runprogram("/.../Run_Forecast.bat");
  2.  
  3. //Execute AFTER batch file has finished
  4. pt("Batch file completed");

Any help would be greatly appreciated, thanks :)

Martin

FlexSim 18.0.3
scriptwaitrunprogrambatch file.bat
5 |100000

Up to 12 attachments (including images) can be used with a maximum of 23.8 MiB each and 47.7 MiB total.

1 Answer

Phil BoBo avatar image
5 Likes"
Phil BoBo answered Phil BoBo commented

I'm not aware of a good way to do this from FlexScript, but you can do it using C++.

The FlexScript command runprogram() is a wrapper around the C++ Windows API WinExec function.

The FlexScript command rundocument() is a wrapper around the C++ Windows API ShellExecute function.

Neither of those commands alone will wait for the spawned process to finish.

In C++, you can use the ShellExecuteEx function in conjunction with the WaitForSingleObject function to execute a batch script and wait for it to finish before moving on. See How to wait for ShellExecute to run?

Something like this:

  1. SHELLEXECUTEINFO sei = {0};
  2. sei.cbSize = sizeof(SHELLEXECUTEINFO);
  3. sei.fMask = SEE_MASK_NOCLOSEPROCESS;
  4. sei.hwnd = NULL;
  5. sei.lpVerb = NULL;
  6. sei.lpFile = "cmd.exe";
  7. sei.lpParameters = apchar(concat("/C \"", modeldir(), "Run_Forecast.bat\""));
  8. sei.lpDirectory = NULL;
  9. sei.nShow = SW_SHOW;
  10. sei.hInstApp = NULL;
  11. ShellExecuteEx(&sei);
  12. WaitForSingleObject(sei.hProcess, INFINITE);
  13. CloseHandle(sei.hProcess);

You could add a C++ user command using the DLL Maker, and call that command from your FlexScript function in order to execute a batch file and not return until it has completed.

wait-for-bat-script-video.zip


· 4
5 |100000

Up to 12 attachments (including images) can be used with a maximum of 23.8 MiB each and 47.7 MiB total.