question

Arne4231-8173 avatar image
0 Votes"
Arne4231-8173 asked ·

How to start a background process and get its PID via CLI

I'm currently writing a program that needs to call another program, retrieve its process id and have it running in the background, independently from the life-cycle of the first program.

To specify further:
- Both programs (small CLI applications) are written in platform-agnostic scripting-languages to realize cross-platform compatibility
- The first program has to get the PID of the second program to be able to stop it
- The second program has to be started in the background, that is, be not visible to the user e.g. as a console window
- The second program has to continue running in case the first program exits
- I have full control over both programs - so if there is a solution that requires an action from the called program, that would be fine
- The solution should use standard Windows features that are available on all modern Windows 10/Server variants

On UNIX-like systems, I can satisfy all requirements like this: nohup my-app --some=argument & echo $!
So what is the closest equivalent on modern Windows?

I have currently two approaches that both cover different requirements:

  1. Using "start /B ..." actually starts the program in the background but does not give me its PID

  2. Using "wmic process call create ..." gives me the PID but starts the program in the foreground with a visible console window

A similar question was already asked in this thread but the implied solution was to just not use the CLI (but a Windows-specific API, I suppose) which is not an ideal solution (for me): https://social.technet.microsoft.com/Forums/en-US/e677abc4-f4d0-4363-af8a-669d074a70d8/minimise-wmic-process?forum=ITCG

windows-10-generalwindows-server-powershell
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

RichMatheisen-8856 avatar image
0 Votes"
RichMatheisen-8856 answered ·

You can use PowerShell's Start-Process from the first program to start the second program. You can then use Get-Process in the first program to acquire the second program's PID. Use the Start-Process's "-WindowStyle" to hide the new process's window.

· 1 ·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thank you for the quick response!

Start-Process actually provides a solution to my problem: powershell.exe -Command "(Start-Process -FilePath ping -ArgumentList google.com -PassThru -WindowStyle Hidden).Id"

0 Votes 0 ·