我有一个在多个 CMD
session 中调用自身的批处理文件,例如:
@echo off
if "%var%"=="set" goto :begin
set var=set
call cmd /c %0
:begin
echo Inside CMD session! Executed under x processes
pause
我想要完成的是获取从中调用批处理文件的进程数。
普通批处理文件:
| Batch-file
| Batch script
将返回 1
,因为正在从根进程调用批处理文件
多进程批处理文件:
| Batch-file
| CMD
| Batch-file
| Batch script
将返回 2
,因为正在从另一个批处理文件调用该批处理文件。
一个可能的解决方案是获取根进程标识符号 (PID),然后分析该进程的等待链,我可以在任务管理器中轻松完成:
总结: 如何返回正在执行批处理文件的进程数,无论是否使用任何第三方实用程序?
最佳答案
@echo off
setlocal
if "%var%"=="3" goto :begin
set /A var+=1
cmd /C "%~F0"
goto :EOF
:begin
echo Inside CMD session!
wmic process where "name='cmd.exe'" get ExecutablePath,ParentProcessId,ProcessId > wmic.txt
for /F "skip=1 tokens=1-3" %%a in ('type wmic.txt') do (
ECHO %%a - Parent: %%b - PID: %%c
set "Parent[%%c]=%%b"
set "This=%%c"
)
set X=0
:nextParent
set /A X+=1
call set "This=%%Parent[%This%]%%"
if defined Parent[%This%] goto nextParent
echo Executed under %X% processes
输出示例:
Inside CMD session!
C:\Windows\system32\cmd.exe - Parent: 3792 - PID: 4416
C:\Windows\system32\cmd.exe - Parent: 4416 - PID: 3220
C:\Windows\system32\cmd.exe - Parent: 3220 - PID: 1728
C:\Windows\system32\cmd.exe - Parent: 1728 - PID: 3560
Executed under 4 processes
关于windows - 找出批处理文件在多少个父进程下运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42598938/