Terminating the external program with system command.

18 views (last 30 days)
Hello,
I am running XFOIL inside the fmincon function. However, xfoil is unstable in some cases. It freezes and MATLAB hangs there forever.
I am using the following code to do timer and taskkill trick, but it does not work:
% Create a timer object
t = timer('StartDelay', 4);
cmd_1 = sprintf(['cd %s && taskkill /IM /F xfoil.exe'],wd);
t.TimerFcn = @(~,~) system(cmd_1);
% Start the timer
start(t);
% execute xfoil
cmd_2 = sprintf(['cd %s && xfoil.exe < "%skill_xfoil_test.inp" > "%skill_xfoil_test.out"'],wd, [wd filesep folder filesep], [wd filesep folder filesep]);
[status,result] = system(cmd_2);
% Stop and delete the timer object
stop(t);
delete(t);
It seems like MATLAB finishes the execution of XFOIL first and then try to kill it.
Does anyone know how to fix this? I appriciate any help.
Thank you!

Answers (2)

Ayush
Ayush on 22 Aug 2023
Here is the possible workaround to ensure MATLAB terminates XFOIL properly:
  • Use ‘system command with appropriate options:
system('xfoil.exe', '-wait');
using ‘-wait’ option MATLAB will not attempt to kill XFOIL until it has finished executing.
  • Timeout mechanism with Tic Toc:
timeout = 60; % Timeout value in seconds
t = tic;
while toc(t) < timeout
% Check if XFOIL has completed
if xfoilCompleted()
break;
end
% Pause for a short duration before checking again
pause(1);
end
In this example, the script waits for XFOIL to complete for a maximum of 60 seconds. If XFOIL has not completed within the timeout period, the script can proceed with the next steps.
Read about Tic and Toc:
  1. https://in.mathworks.com/help/matlab/ref/tic.html
  2. https://in.mathworks.com/help/matlab/ref/toc.html

Walter Roberson
Walter Roberson on 22 Aug 2023
Edited: Walter Roberson on 22 Aug 2023
On Windows systems, there is an alternate mechanism.
If you use the .NET System.Diagnostics.Process interface, you can start processes running asynchronously, with MATLAB still running. You can have timers and detect whether the process finished, and if not then you can use the S.D.P interface to cancel the process. You would not use system() to start the process and you would not use system() to terminate the process if need be.
This interface is not supported on Mac or Linux.
(On the other hand, MacOS and Linux do not use taskmgr ...)

Categories

Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!