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

Arne4231 21 Reputation points
2021-03-12T11:19:26.283+00:00

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 for business | Windows Server | User experience | PowerShell
Windows for business | Windows Client for IT Pros | User experience | Other
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 47,901 Reputation points
    2021-03-12T15:49:44.117+00:00

    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.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.