Adding a MATLAB process to a Windows JOB

2 views (last 30 days)
Marco Foco
Marco Foco on 10 Sep 2014
In a C++ application I'm creating one or more MATLAB engines (via engOpenSingleUse) and use them several times. I would the MATLAB processes to be closed either when my application is closed, or it crashes. I can achieve easily the first solution (by keeping track of the engines opened by the application), but I can't intercept all the crashes reliably.
In windows there's a mechanism (Jobs) that will do exactly this, but in order to work I have to: - Create a job by calling CreateJob function and then setting some specific flags (JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE) - Create a process by calling CreateProcess function and setting the CREATE_BREAKAWAY_FROM_JOB flag in the creation flags
I already have several processes added to this job, and they all shut down correctly when the program crashes, but for MATLAB this solution doesn't hold, since the responsibility of creating the process is delegated to the engOpenSingleUse function, and I have no control over those flags.
One solution I see is to launch the MATLAB process with the correct flags (see code below) and then connect to that engine, but I don't know how to do it.
Are there other solutions?
I attach the working C++ code I use to create the Job and Processes (but not the MATLAB process):
JOBOBJECT_EXTENDED_LIMIT_INFORMATION eli = {0};
HANDLE job = CreateJobObject(NULL, NULL);
eli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
SetInformationJobObject(job, JobObjectExtendedLimitInformation, &eli, sizeof(eli));
And here's the code to create the (other) processes:
PROCESS_INFORMATION piProcInfo;
STARTUPINFO siStartInfo;
// Omissis: some code to set up members of siStartInfo
// and to clean up piProcInfo.
CreateProcess(NULL,
procName,// command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
CREATE_BREAKAWAY_FROM_JOB, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
And finally I assign the process to the job:
AssignProcessToJobObject(job, piProcInfo.hProcess);
Marco Foco

Answers (0)

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!