How can I get the PID of the process created by the 'system' command on Windows platform?
19 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
MathWorks Support Team
am 23 Feb. 2024
Beantwortet: MathWorks Support Team
am 23 Feb. 2024
How can I get the PID of the process created by the 'system' command on Windows platform?
system('myprogram.exe');
Akzeptierte Antwort
MathWorks Support Team
am 23 Feb. 2024
At present, there is no direct way of obtaining the PID of the process. I have forwarded your feedback for this functionality to be implemented to the development team. It may be considered for implementation in a future release of MATLAB software.
On Windows, there are several possible workarounds you can try on your end.
1. The following MATLAB command gives you processes with "MATLAB" in their name
>> !tasklist | findstr -i "MATLAB"
You can change "MATLAB" to your exe name and it should give you the PID of that exe.
2. The following MATLAB command gives you the children PIDs of MATLAB:
>> system(sprintf('wmic process where (ParentProcessId=%d) get Caption,ProcessId', feature( 'getpid' )))
.
3. The following more elaborate code can be used to find the exact PID of the command line shell opened by MATLAB:
% For example, launch batchfile from MATLAB
system('batchfile.bat &');
% Get PID of CMD shell
batFileName = 'batchfile.bat';
matlabpid = num2str(feature('getpid'));
query = ['wmic process where "name=''cmd.exe'' and parentprocessid=' matlabpid ' and commandline like ''%%cmd /D /k \"' batFileName '\"%%''" get processid /format:list'];
[~,batpidquery] = system(query);
batpid = regexp(batpidquery, '\d+', 'match', 'once');
% Use the PID to terminate the process
[a,b] = system(['taskkill /F /PID ' batpid]);
The idea of the code is to identify the launched cmd.exe process by the parent PID of MATLAB, and the command that was issued by MATLAB (in this case, the batch file name).
For example, assuming MATLAB's PID is 8420, the following system command will be used to obtain the PID of the CMD shell opened by MATLAB:
wmic process where "name='cmd.exe' and parentprocessid=8420 and commandline like '%%cmd /D /k \"batchfile.bat\"%%'" get processid /format:list
The above has been tested on Windows 10.
Other related articles:
0 Kommentare
Weitere Antworten (0)
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!