MATLAB: MATLAB fails to launch from Swift-based application

desktopMATLABnodesktopstdinterminates

I am trying to spawn a MATLAB instance from a external program (in this specific case, a Swift GUI Application on a MacOS system). When the external program launches MATLAB, the MATLAB process will start, the splash screen will appear, and then suddenly MATLAB will terminate before the desktop opens.
Why does MATLAB suddenly terminate when launched from a external application, and how can this be prevented?

Best Answer

MATLAB is being terminated suddenly when launched from a external application because the MATLAB process needs commands to read from a controlling process. If MATLAB does not have commands to read, it will terminate.
Workarounds to prevent MATLAB from terminating are:
If you need to launch MATLAB with its desktop open:
Workaround: Launch MATLAB with the "-desktop" startup option.
Note the "-desktop" startup option documentation:
"Allows the MATLAB desktop to be started by a process without a controlling terminal. This is usually a required command line argument when attempting to start MATLAB from a window manager menu or desktop icon."
If you need to launch MATLAB without a desktop open:
Workaround: Launch MATLAB with the "-nodesktop" startup option, and spawn the MATLAB process with a open "Pipe" to its standard input (stdin), and ensure the standard input remains open for the duration of the MATLAB process.