Forum Discussion
How to write a script to start a Docker container and stop WSL safely when the container stops?
There's no single, generic way to know that.
At best, there might be a way that's specific to the exact application/service you're working with, but for another application/service, it might require a completely different approach - or there may be no way at all. It's not like Windows prescribes a standard that client processes have to confirm to/integrate with.
Take Docker, for example. If the "Docker Desktop" you're launching were to in turn launch (or stop) child processes of its own, then you could leverage that behaviour. But let's say it doesn't, then you may have no visibility into how it's going with its start-up routine at which point all you can do is wait an arbitrary interval (or variations of that such as polling, but this isn't always materially any better).
Cheers,
Lain
I see. So if an app wants to implement this, what would be the way for it to do so? What teens should I look for?
- LainRobertsonSep 07, 2023Silver Contributor
I don't quite understand the question. What are teens? (Excluding rambunctious kids.)
Cheers,
Lain
- ookerSep 07, 2023Copper Contributor
oh it's autocorrect
. I was asking "what terms should I look for?"- LainRobertsonSep 07, 2023Silver Contributor
I can't tell you what to look for with Docker, as I don't use it.
The best I can do is provide you with a hypothetical example for a scenario where the first program you start with Start-Process (in your case, this is Docker Desktop) then starts another child process of its own, indicating it's operational.
Because I don't use Docker, I have to use other programs in the example. Here's a table that translates what I'm using for illustrative purposes to what you would use.
Stage My example Your scenario Start-Process cmd.exe Docker Desktop Child process notepad.exe <something Docker launches> Example
# Launch the "main" process. $Process = Start-Process -FilePath "cmd.exe" -PassThru -ErrorAction:Stop; # Monitor for a specific child process being launched by the main process. $CheckAgain = $true; $Retries = 10; while ($CheckAgain -and ($Retries -gt 0)) { if (Get-CimInstance -ClassName "Win32_Process" -Filter "ParentProcessID=$($Process.Id) AND Name='notepad.exe'") { $CheckAgain = $false; } else { $Retries--; Start-Sleep -Seconds 2; } }Here, we're checking for a maximum of 20 seconds ([10 retries] x [two second sleep] to see if the child process has started. If it starts earlier, then the loop will exit earlier.
But again, this is hypothetical and may not be useful for your Docker scenario at all. You'd have to do some investigating to see how Docker behaves before you can solve your challenge.
Cheers,
Lain