views:

159

answers:

1

Hi!

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?

+1  A: 

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)

ghostdog74
Can I assume VBScript to be installed on any windows machine?
Manfred Moser
yes. win9x onwards
ghostdog74
WSH didn't originally ship with Windows 95, although you could easily obtain it separately, and I'm pretty sure the later OEM releases of 95, as well as all releases of 98, did include it. In any case, I would assume its presence; Windows 95 support has been officially discontinued for nearly a decade now.
ephemient