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 10
Windows 10
A Microsoft operating system that runs on personal computers and tablets.
10,660 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,381 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 45,091 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