How to execute a dos command from MATLAB and return control immediately to MATLAB (without spawning a dos window)

demarcmj picture demarcmj · Jan 19, 2012 · Viewed 15.8k times · Source

I want to execute a batch file in dos from MATLAB and have control returned immediately to MATLAB. However, I want to do this without opening up a dos window (or, at the very least, get the dos window to disappear at the end).

If I format my command like this...

s = dos('batchfilename.bat');

then MATLAB runs the batch file without opening up a dos window, but the MATLAB code has to wait for the return.

If I format my command like this...

s = dos('batchfilename.bat &');

Control is returned immediately to MATLAB, but it also displays the dos window, which I don't want. (It's also difficult to detect when the batch file is "done" when you do it this way)

Any help would be appreciated.

Answer

Andrew Janke picture Andrew Janke · Jan 19, 2012

Use Matlab's External Interfaces support to get access to a lower level language's process control features.

.NET Version

Use the .NET System.Diagnostics.Process class. It'll let you run a process asynchronously, check for when it's exited, and collect the exit code. And you can optionally hide its window or leave it visible for debugging.

You can call .NET classes directly from M-code.

function launch_a_bat_file()
%//LAUNCH_A_BAT_FYLE Run a bat file with asynchronous process control

batFile = 'c:\temp\example.bat';
startInfo = System.Diagnostics.ProcessStartInfo('cmd.exe', sprintf('/c "%s"', batFile));
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;  %// if you want it invisible
proc = System.Diagnostics.Process.Start(startInfo);
if isempty(proc)
    error('Failed to launch process');
end
while true
    if proc.HasExited
        fprintf('\nProcess exited with status %d\n', proc.ExitCode);
        break
    end
    fprintf('.');
    pause(.1);
end

Java Version

The .NET version requires a Matlab new enough to have .NET support. Here's a Java-based version for older Matlabs, like OP turns out to have. Should also work on non-Windows systems with a bit of modification.

function launch_a_bat_file_with_java
%LAUNCH_A_BAT_FILE_WITH_JAVA  Java-based version for old Matlab versions

batFile = 'c:\temp\example.bat';
cmd = sprintf('cmd.exe /c "%s"', batFile);
runtime = java.lang.Runtime.getRuntime();
proc = runtime.exec(cmd);

while true
    try
        exitCode = proc.exitValue();
        fprintf('\nProcess exited with status %d\n', exitCode);
        break;
    catch
        err = lasterror(); % old syntax for compatibility
        if strfind(err.message, 'process has not exited')
            fprintf('.');
            pause(.1);
        else
            rethrow(err);
        end
    end
end

You may need to fiddle with the I/O in the Java version to avoid hanging the launched process; demarcmj notes that you need to read and flush the Process's input stream for stdout to avoid it filling up.