Search code examples
bashmatlabunixpid

Cancelling a unix process started by matlab


Hi I'm trying to run a process xfoil in this case from matlab. The problem is sometimes xfoil crashes so to carry on without issue I need to run it as a background process. However now I end up with a race condition where xfoil hasn't finished by the time the data is needed. To solve this I added a pause statement, but in many cases the pause is too long. What I would like to do is record the process id when starting then within a while loop check if the process still exists. For windows this is accomplished like so.

elseif(ispc)
    run_xfoil_command='start /b xfoil.exe < foilcommands > dump.out';
    [~,~] = system(run_xfoil_command);
    tic;
    % While xfoil hasn't finished running
    while (system('tasklist /FI "IMAGENAME eq xfoil.exe" 2>NUL | find /I /N "xfoil.exe">NUL')==0)
        if (toc>5)
            [~,~] = system('taskkill /F /IM xfoil.exe > dump1.out');
            break
        end
        pause(0.2);
    end
    [~,~] = system('taskkill /F /IM cmd.exe > dump1.out');
end

However I can't figure out how to accomplish this in linux. I've tried;

if(isunix)
    run_xfoil_command='pidof xfoil < foilcommands > dump.out &';
    setenv('GFORTRAN_STDIN_UNIT', '5')
    setenv('GFORTRAN_STDOUT_UNIT', '6')
    setenv('GFORTRAN_STDERR_UNIT', '0')
    tic;
    [stat,pid] = unix(run_xfoil_command)

However the process id is not returned in either pid, or the dump.out. Can anyone help to solve this issue. Thanks.


Solution

  • As I said in my comment, pidof only gets the pid of a running program. If the command xfoil is what gets your program running, you should try

    xfoil < foilcommands &; /sbin/pidof xfoil > dump.out
    

    Then check the contents of dump.out. I think your pid will be there...