Hi guys,
I would like to know if there is a trick to get a .bat file PID. Apart from "converting" the file to .exe I don't know how to get the matching PID among all the cmd.exe & conhost.exe processes, that would be very useful to me.
Thank you in advance.
batch file PID
Moderator: DosItHelp
Re: batch file PID
It becomes Very easy if you use a title to flag your script.
The randomised UID isn't strictly necessary, however simplifies isolation of a given instance of the script should multiple instances be running.
Code: Select all
@Echo off
Set /A UID=%random% %% 10000
Title %~n0_%UID%
2> nul (For /F "tokens=2 Delims=: " %%G in ( 'Tasklist /Fi "windowtitle eq %~n0_%UID%" /Fi "imagename eq cmd.exe" /FO:List ^| Findstr.exe /LIC:"PID"' )Do Set "%~n0_%UID%=%%G")
Set %~n0_%UID%
Re: batch file PID
Ensuring the titles differ is necessary if there is a chance the script may be run in multiple instances at the same time. Unfortunately %RANDOM% is not good enough because two CMD sessions that are started within the same second will always get the same random number - the cmd.exe seed for the random number generator is derived from the time.
Years ago I wrote a bullet proof solution for a batch file to determine its own PID: viewtopic.php?p=38870#p38870. It uses a lock file to guarantee there is no confusion between two processes started at the same time.
Dave Benham
Re: batch file PID
Very robust indeed.dbenham wrote: ↑08 Nov 2020 06:07Ensuring the titles differ is necessary if there is a chance the script may be run in multiple instances at the same time. Unfortunately %RANDOM% is not good enough because two CMD sessions that are started within the same second will always get the same random number - the cmd.exe seed for the random number generator is derived from the time.
Years ago I wrote a bullet proof solution for a batch file to determine its own PID: viewtopic.php?p=38870#p38870. It uses a lock file to guarantee there is no confusion between two processes started at the same time.
Dave Benham
Re: batch file PID
https://github.com/npocmaka/batch.scrip ... CmdPID.bat - you can try with this. It saves the PID to the errorlevel
-
- Posts: 21
- Joined: 04 Aug 2017 14:20
- Location: France
Re: batch file PID
My problem is solved thanks to you.
Thank you all for your answers, have a good week.
Thank you all for your answers, have a good week.
Re: batch file PID
Alternative:
(based on this thread )
EDIT:
Never mind; a similar solution was already mentioned in one of the linked threads ....
Code: Select all
for /f "tokens=2 delims==" %%i in (
'wmic process WHERE ^"CommandLine LIKE '%comspec:\=\\% /c wmic process WHERE \^"CommandLine LIKE%%'^" get ParentProcessId /value'
) do set "PID=%%i"
EDIT:
Never mind; a similar solution was already mentioned in one of the linked threads ....