Terminating the external program with system command.

17 次查看(过去 30 天)
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!

回答(2 个)

Ayush
Ayush 2023-8-22
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 2023-8-22
编辑:Walter Roberson 2023-8-22
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 ...)

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by