简体   繁体   中英

How do I write a pidfile in a windows batch file

I am writing some Java code that needs to be able to write a pidfile on Unix-like as well as windows machines. On the unix machines I write out a bash shell script that contains something like this

command 1>/dev/null 2>&1 &
echo $! > pidfile

It executes a command, redirects all output into nirwana and puts command into the background (detaches it from the shell). The pidfile contains the process id of the command. I can then later go and read the process id out of the file. That all works fine.

Now on Windows I think I should do something like

start command

and then somehow the equivalent for the Unix way. Problem is I have no control where the program will be used in terms of windows version or what is installed on the machine. I also don't have access to a Windows machine to test things out and I could not find anything simple on the web. I know there is the get-process function in powershell but I do not know if powershell will be installed on the machine so I can't rely on that.

Is there some simple DOS batch file command or syntax that does what I need?

you could use a vbscript

Set objFS = CreateObject("Scripting.FileSystemObject")
Set objArgs = WScript.Arguments
strProcess = objArgs(0)
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2:Win32_Process")

Error = objWMIService.Create(strProcess, null, null, intProcessID)
If Error = 0 Then
    Wscript.Echo intProcessID 
Else
    Wscript.Echo Error
End If

on the command line, say if you want to execute notepad:

c:\test> cscript //nologo mycreatepid.vbs "notepad.exe"
3120

you can capture the return value in a batch file using a for loop. (Otherwise, you can learn to use vbscript and do everything in vbscript)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM