How can I process an external System Signal in a Matlab executable

2 ビュー (過去 30 日間)
Thomas Pfau
Thomas Pfau 2014 年 11 月 4 日
回答済み: Swastik Sarkar 2024 年 9 月 18 日
Hello,
I'm creating a Matlab executable via mcc to run a tool on a cluster (in a linux environment). I have a situation, where it is necessary to be able to checkpoint my computation and graceously exit when a given external signal is received. I saw that there is the onCleanup function, which works nicely within Matlab. However when the code is compiled as an executable onCleanup does not react to any external signals. Regardless on whether I send a signal to the process via kill or just press ctrl+c in the terminal running the code it just terminates without executing the cleanup. Unfortunately I haven't found any other method to handle external events (maybe I just looked in the wrong places).
Could anyone tell me whether there is a way to handle external signals in a matlab executable?
  1 件のコメント
Ken
Ken 2017 年 9 月 4 日
I have the exact same issue. Is there any practical solution?

サインインしてコメントする。

回答 (1 件)

Swastik Sarkar
Swastik Sarkar 2024 年 9 月 18 日
Consider a simple MATLAB function named action that includes an onCleanup function:
function action
x = onCleanup( @() fprintf('perform cleanup here...\n') );
for ii=1:1000, disp(ii), pause(1), end
When compiling this MATLAB application with mcc and executing it, the behavior is similar to running:
matlab -batch action
Pressing Ctrl+C during execution will not trigger the onCleanup function. However, similar functionality can be achieved by editing the shell script provided after compilation with mcc. This involves capturing the signal using trap and performing the necessary cleanup. An example bash script might look like this:
#!/bin/sh
cleanup()
{
echo "Cleaning up !"
exit 1
}
trap cleanup INT
exe_name=$0
exe_dir=`dirname "$0"`
echo "------------------------------------------"
if [ "x$1" = "x" ]; then
echo Usage:
echo $0 \<deployedMCRroot\> args
else
echo Setting up environment variables
MCRROOT="$1"
echo ---
LD_LIBRARY_PATH=.:${MCRROOT}/runtime/glnxa64 ;
LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${MCRROOT}/bin/glnxa64 ;
LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${MCRROOT}/sys/os/glnxa64;
LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${MCRROOT}/sys/opengl/lib/glnxa64;
export LD_LIBRARY_PATH;
echo LD_LIBRARY_PATH is ${LD_LIBRARY_PATH};
shift 1
args=
while [ $# -gt 0 ]; do
token=$1
args="${args} \"${token}\""
shift
done
eval "\"${exe_dir}/action\"" $args
fi
exit
Executing the script results in:
1
2
3
4
5
6
^CCleaning up !
This approach should help in managing cleanup operations effectively when the application is interrupted.
I hope this helps !

カテゴリ

Help Center および File ExchangePulsed Waveforms についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by