How to get PID from a current process

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
miskox
Posts: 668
Joined: 28 Jun 2010 03:46

How to get PID from a current process

#1 Post by miskox » 22 Nov 2012 06:06

There are many topics regarding this but not single one answers my question. Is there a way to easly get the PID of a current process. Something like this:

Code: Select all

@echo off
set mypid=%PID%


%PID% would be a system variable containing PID of a process asking for it.
If you are familiar with OpenVMS here is its equivalent:


Code: Select all

$ mypid=F$GETJPI ("","PID")


I don't want to use tasklist because:
- if I make a tasklist search for an image name (or a window title) there is a chance that there is more than one on the system with the same name

Can WMIC do this?

If not then I guess TASKLIST would do the job (based on viewtopic.php?p=21175#p21175):

Code: Select all

@echo off
set titl=RANDOMTITLE%RANDOM%
title %titl%
for /f tokens^=3^ delims^=^" %%a in ('tasklist /nh /v /fi "WINDOWTITLE eq %titl%" /fo csv') do (
echo %%a
)


The problem is that there is a chance that two TITLEs are the same on the system.
So if there is another way that would be great.
Then I guess always adding some more %RANDOM% numbers to the TITLE would elimiate the chance of making two identical TITLEs on the system.

The main reason why I need this is that this is the only unique number on the system so I can use it in temporary filenames. Using %RANDOM% in a batch file is not 100% secure method. PID is because not two processes can have identical PIDs.

Thanks,
Saso
Last edited by miskox on 22 Nov 2012 10:34, edited 1 time in total.

abc0502
Posts: 1007
Joined: 26 Oct 2011 22:38
Location: Egypt

Re: How to get PID from a current process

#2 Post by abc0502 » 22 Nov 2012 06:36

In this code you provide the application name "process name" and it give you all the PID numbers of the match names:

Code: Select all

@echo off
for /f "skip=1 tokens=*" %%i in ('wmic process where name^="chrome.exe" get Processid') do echo %%i
pause

I don't now if that what you searching for, but it use the wmic.

Edit:
in wmic, type process get, and it will give you all switches related to the processes

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: How to get PID from a current process

#3 Post by foxidrive » 22 Nov 2012 06:44

miskox wrote:The main reason why I need this is that this is the only unique number on the system so I can use it in temporary filenames. Using %RANDOM% in a batch file is not 100% secure method.


This is a reliable method, unless you foresee 100,000 temp files using the same naming scheme.

:loop
set "tempfile=%temp%\file.%random%.tmp"
if exist "%tempfile%" goto :loop

miskox
Posts: 668
Joined: 28 Jun 2010 03:46

Re: How to get PID from a current process

#4 Post by miskox » 22 Nov 2012 10:43

@foxidrive: RANDOM returns a number between 0 and 32767. So in theory it is likely that another process can get the same random number. In such case there might be a problem with temporary files - two different processes would want to access the same file.

@abc: searching for a process name is not reliable. When I start a .cmd file its process name is cmd.exe. So I can't find the correct one. All .cmd processes have the same process name (cmd.exe).

This is the only reason why I would like to get a PID. 100% unique for each process on the system.

Any more ideas?

Thanks,
Saso

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: How to get PID from a current process

#5 Post by foxidrive » 22 Nov 2012 10:59

miskox wrote:@foxidrive: RANDOM returns a number between 0 and 32767. So in theory it is likely that another process can get the same random number.


Yes, not 100,000 but more than 32,000 choices.

A second program will not use the same filename you have chosen, using the routine I outlined, unless the second program uses hard coded filenames.

There is a second factor to consider and that is the filename itself.
You can use a sufficiently unqiue filename such as "$#$@miscoxtemp%random%.tmp" and I doubt that would be selected by any other tool.

This is the only reason why I would like to get a PID. 100% unique for each process on the system.


But a PID is just aset of digits and when used in a filename it is no longer a PID but a simple number. It can exist in the temp folder too.

Isn't that the task, to create a unique filename?

miskox
Posts: 668
Joined: 28 Jun 2010 03:46

Re: How to get PID from a current process

#6 Post by miskox » 22 Nov 2012 11:40

Yes,the main purpouse is to create unique temp files.

Let's say I have a .cmd file which I can run n-times from the same folder (or if run from different locations temp files are created in %temp%) so I want to make unique filenames. No matter what I write in the filename (fixed part of a filename) the only difference is the 'random' part (RANDOM or PID). And here lies the problem.
I want to avoid problems where temp files are written in the same folder.

Code: Select all

set tempfile=tempfile%random%.tmp
"do whatever with this tempfile..."


There is a chance that problems will occur if the code above is run n-times simultaneously.

Code: Select all

set tempfile=tempfile%PID%.tmp
"do whatever with this tempfile..."


No way there will be a problem if PID is used.

Thanks,
Saso

Aacini
Expert
Posts: 1932
Joined: 06 Dec 2011 22:15
Location: México City, México
Contact:

Re: How to get PID from a current process

#7 Post by Aacini » 22 Nov 2012 12:18

I suppose I could modify my Window.exe auxiliary program to return the PID in ERRORLEVEL this way:

Code: Select all

Window PID
Wait for it later today...

Antonio

Ed Dyreen
Expert
Posts: 1569
Joined: 16 May 2011 08:21
Location: Flanders(Belgium)
Contact:

Re: How to get PID from a current process

#8 Post by Ed Dyreen » 22 Nov 2012 16:02

'
Another solution is to retrieve myPID from cmdow.EXE

Code: Select all

cmdow.EXE @

Code: Select all

for /f "skip=1tokens=3" %%? in ('"!$cmdow.file!" @') do set "myPID=%%?"

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: How to get PID from a current process

#9 Post by foxidrive » 22 Nov 2012 16:15

miskox wrote:Yes,the main purpouse is to create unique temp files.

Let's say I have a .cmd file which I can run n-times from the same folder (or if run from different locations temp files are created in %temp%) so I want to make unique filenames. No matter what I write in the filename (fixed part of a filename) the only difference is the 'random' part (RANDOM or PID). And here lies the problem.
I want to avoid problems where temp files are written in the same folder.

Code: Select all

set tempfile=tempfile%random%.tmp
"do whatever with this tempfile..."


There is a chance that problems will occur if the code above is run n-times simultaneously.

Code: Select all

set tempfile=tempfile%PID%.tmp
"do whatever with this tempfile..."


No way there will be a problem if PID is used.

Thanks,
Saso


Why is there any difference when using the PID? I don't see that as being any better than checking to see if the %random% fileset exists and looping to pick a different number.

For example, there could already be a tempfile%PID%.tmp in the folder.

abc0502
Posts: 1007
Joined: 26 Oct 2011 22:38
Location: Egypt

Re: How to get PID from a current process

#10 Post by abc0502 » 22 Nov 2012 17:38

If it all about generating random numbers, any math formula using + * / - and few conditions to prevent dividing on zero may do the trick.

There is a sequence called "Hailstone Sequence", It generate a list of numbers based on if it was dividable or not, something like that could be used to generate
random numbers.

I'm trying to do that in batch, but as i said a math formula can do that especially if it was consisted of 3 or 4 parts joined together.

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: How to get PID from a current process

#11 Post by foxidrive » 22 Nov 2012 17:43

Nice to see you back abc0502.

Were you on holiday? :)

abc0502
Posts: 1007
Joined: 26 Oct 2011 22:38
Location: Egypt

Re: How to get PID from a current process

#12 Post by abc0502 » 22 Nov 2012 20:21

foxidrive wrote:Nice to see you back abc0502.
Were you on holiday? :)

well, it wasn't a exactly a holiday, i was busy finishing some paper related to my collage.
what can i say Bureaucracy :evil:

About the hailstone sequence,
I tried many ways but keep giving me missing operator error so i searched the net and found this Link
it really works great, but i realized that it will be useless because if the start number was repeated it will give the same sequence and then we will be in the same problem ?? :?

Till now this is what i can say it works:

Code: Select all

@echo off
setlocal enabledelayedexpansion
For /L %%a in (1,1,5) Do <nul set /p "=!RANDOM!"
echo.
pause
This will generate 5 random numbers and put them together to output one long random number

I tested using 10001 long random number using this code:

Code: Select all

@echo off
setlocal enabledelayedexpansion
For /L %%A in (1,1,10000) Do (
   For /L %%a in (1,1,5) Do <nul set /p "=!RANDOM!">>list.log
   echo.>>list.log
   )
echo.
pause

And by removing the duplicates using this:

Code: Select all

type nul>only_new.txt
for /f "tokens=* delims=" %%a in (list.log) do (
  findstr /ixc:"%%a" only_new.txt >nul || >>only_new.txt echo.%%a
)


The Result:
Repeated Numbers was = 0 of total 10001 ---> 0%
Non-Repeated Numbers was = 10001 of total 10001 ---> 100%

by raising the number 5 in the for loop to higher number you will reduce the chance to have a repeated numbers and the opposite by reducing number 5

I hope that help :)

Liviu
Expert
Posts: 470
Joined: 13 Jan 2012 21:24

Re: How to get PID from a current process

#13 Post by Liviu » 22 Nov 2012 22:00

miskox wrote:This is the only reason why I would like to get a PID. 100% unique for each process on the system.

PIDs are not guaranteed to be truly unique, unless you mean (a) among the currently running processes, (b) on a completely isolated system. Without the former, a PID could have belonged to a previously run process. Without the latter, the PID could come from another system - like a networked machine with access to the same directory, but also less obvious cases such as an "xp mode" virtual machine under win7 x64.

Several MS development packages (windows sdk, visual studio/express) come with a command line uuidgen.exe, which is as close as it gets to the "uniqueness" requirement. If you happen to have one of those installed, using uuidgen in a batch is as easy as from the command line.

Code: Select all

C:\tmp>for /l %n in (1,1,5) do @for /f %u in ('uuidgen') do @echo %u
8b643c4d-d53e-43ea-871d-13a8f1e63748
5acd86a4-93cf-4e5d-9c10-2d6c02ff565f
56417615-1620-4556-b2b8-8aaf34094a8b
bc02f2f0-dc25-455c-adca-ea6873a85940
683af327-ebda-43f8-ac80-d19e08c2e652

Liviu

P.S. Bookmarked a few recent exciting threads for when I get more time on my hands. Thanks to the usual suspects ;-) And Happy Thanksgiving, all!

miskox
Posts: 668
Joined: 28 Jun 2010 03:46

Re: How to get PID from a current process

#14 Post by miskox » 23 Nov 2012 13:24

Thank you all for your replies.

@abc: here is your procedure in two different files:

a.cmd

Code: Select all

@echo off
setlocal enabledelayedexpansion
For /L %%A in (1,1,10000) Do (
   For /L %%a in (1,1,5) Do <nul set /p "=!RANDOM!">>lista.log
   echo.>>lista.log
   )
echo.


b.cmd

Code: Select all

@echo off
setlocal enabledelayedexpansion
For /L %%A in (1,1,10000) Do (
   For /L %%a in (1,1,5) Do <nul set /p "=!RANDOM!">>listb.log
   echo.>>listb.log
   )
echo.


As you can see files are the same. The only difference is the output filename.

Now, start them with:

Code: Select all

start "" a.cmd&start "" b.cmd


I did a binary compare. And know what? ListA.log and ListB.log are identical. They were run from two different processes. The reason is probably the same parent process (so they have the same 'seed').
If I run them from two different cmd instances I get this:

Count duplicate records:

Code: Select all

@echo off
del duplicates.log >nul 2>nul
set /a cnt=0
for /f "tokens=1 delims=" %%f in (lista.log) do call :delaj %%f
echo %cnt% records are in both files.
echo See duplicates.log
goto :eof

:delaj
find "%1" listb.log&&(set /a cnt=cnt + 1&echo %1>>duplicates.log)
goto :EOF

Number of duplicate entries: don't know. My computer is too slow to finish quickly. But few searches revealed the same result as abc's: 0 matches.

So (also what I wrote in my original post) one good solution (without 3rd party programs) is to use multiple RANDOMs.

@liviu: yes, you are right about the network processes etc. In my case there would be a single computer and with a chance of running many .cmd files at once.
Regarding old PID numbers: I would assume that the system would increment PID numbers but I never tested that. Why would the system recycle PID numbers?

The current PID number would be required as long as the current (.cmd) process is executing. In this case new processes cannot have the same process number at all. When current process finishes it deletes all the temporary files.

@ed: I never tried that cmdow.exe. I might do that sometime.

To sum it up: to use multiple RANDOM numbers is the easiest way (together with a current %DATE% %TIME%. What is the chance that two (or more) processes are run exactly at the same time (to the hundredth of a second))?

Thank you all.
Saso

Liviu
Expert
Posts: 470
Joined: 13 Jan 2012 21:24

Re: How to get PID from a current process

#15 Post by Liviu » 23 Nov 2012 17:02

miskox wrote:Regarding old PID numbers: I would assume that the system would increment PID numbers but I never tested that. Why would the system recycle PID numbers?

PIDs are not assigned sequentially, and they are reused. There is no guarantee other than the PIDs of running processes being mutually distinct at any one moment in time. (Off-topic side note: this is why it's technically not possible to find out the parent process of a running process reliably, since all Windows remembers is the parent process ID, which may have become invalid, or been reassigned in the meantime.)

Liviu

Post Reply