Safer alternative to MATLAB's `system` command
linux, matlab
Solution
Thanks goes to Andrew Janke for helping me find this solution.
To easily reproduce the error we can run the command:
[ret, out] = system('sleep 2');
If we type some characters while this is running, the `out` variable will be contaminated with what we typed.
The solution to this problem is to redirect stdin from /dev/null like the following:
[ret, out] = system('sleep 2 < /dev/null');
This stops the `out` variable from being contaminated by user input.
Interestingly though this seems to fix the original test-case for the current MATLAB session (tested on R2014a OSX and R2013b Linux) so if we do another `[ret, out] = system('sleep 2');` the output is no longer contaminated by user input.
Problem
I have been using MATLAB's `system` command to get the result of some linux commands, like in the following simple example: ``` [junk, result] = system('find ~/ -type f') ``` This works as expected, unless the user types into MATLAB's command window at the same time. Which during a long `find` command is not uncommon. If this happens then the user's input seems to get mixed up with the result of the `find` command (and then things break). As an example, instead of: ``` /path/to/file/one /path/to/file/two /path/to/file/three /path/to/file/four ``` I might get: ``` J/path/to/file/one u/path/to/file/two n/path/to/file/three k/path/to/file/four ``` In order to demonstrate this easily, we can run something like: ``` [junk, result] = system('cat') ``` Type something into the command window and press CTRL+D to close the stream. The `result` variable will be whatever you typed in to the command window. Is there a safer way for me to call system commands from MATLAB without risking corrupted input?