[Matlab] Quit or Exit External Process with Matlab

Sometimes you just want to kill any process that you are running from matlab. This process has to run within Matlab or be Matlab itself, otherwise it is impossible. Therefore you can run an external script to quit an external process – which is the only way. I tried going with the native Matlab Java stuff but that didnt work at all. Then i tried using Perl, and i got a fancy script here that can quit any process you want, given that you have the process’s name.

In the below case, i quit the external process “gphoto2.exe” from Matlab. My problem was that i could call gphoto2.exe, and it might stay alive – then i couldnt call a new one because the older one was alive but it was branched into an unreachable process when i cleared the Matlab environment variable. Anyway here you go!

Also, maybe I should say this is for Windows (32/64), this is Not for Mac or Unix/Linux based systems. If you are running such a system and you don’t know how a kill a process from there you are an utter idiot.

Matlab Side

Call this from anywhere in Matlab (given that the folder where the below script is saved is actually added in your path).

perl('quitproc.pl','gphoto2.exe');

Perl Side

save this in a file called quitproc.pl .

#(c) Tim Zaman 2012
 
use warnings;
use strict;
 
use Win32::OLE qw(in);
 
my($input) = $ARGV[0];
my $exitcode;
 
my $objWMI = Win32::OLE->GetObject('winmgmts://./root/cimv2');
my $procs = $objWMI->InstancesOf('Win32_Process');
 
my @hits;
foreach my $p (in $procs) {
#push @hits => [ $p->Name, $p->ProcessID ]
    if($p->Name eq $input){
        my($pidnow)=int($p->ProcessID);
        my($procnow)=$p->Name;
        #Now we kill the process
        kill 9, $pidnow; #SIGQUIT (quit signal) = 9
        print "Quit process: ", $procnow, ' (', $pidnow ,")n";
    }
}

Tim Zaman

MSc Biorobotics. Specialization in computer vision and deep learning. Works at NVIDIA.

You may also like...

2 Responses

  1. Daniel says:

    Hi Tim,
    this is exactly what I was looking for.
    The post clearly explains what and how it should be done.
    Thank you very much for sharing the code.