- 1 year ago
Windows shell script exit child processes on shell close?
In Windows, when you run a shell script or batch script, child processes spawned by that script will not be automatically terminated when the script itself is closed or terminated. Each process, including child processes, has its own process ID (PID) and runs independently.
If you want to ensure that child processes are terminated when the parent script is closed, you can consider the following approaches:
Trap Signals in Batch Script (Windows Shell):
Batch scripts don't have built-in signal handling like Unix shell scripts, but you can create a custom signal handler by checking if the script is running in the foreground or background and then terminating the child processes accordingly. Here's a basic example:batch@echo off
setlocal
set "child_pid=0"
start "" cmd /c "child_script.bat" & set "child_pid=%^$%"
echo Parent script running, press any key to exit...
pause > nul
if %child_pid% neq 0 (
taskkill /F /PID %child_pid%
)
endlocal
In this example, replace
child_script.bat
with the actual name of your child script. The parent script starts the child script in a separate command prompt and stores its PID. When the parent script is closed usingpause
, it checks if the child PID is not zero and terminates the child process.Using PowerShell Script:
PowerShell scripts provide more advanced control over processes. You can use theStart-Process
cmdlet to start child processes and then useStop-Process
to terminate them. Here's an example:powershell$childProcess = Start-Process -FilePath "child_script.bat" -PassThru
Write-Host "Parent script running, press any key to exit..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Stop-Process -Id $childProcess.Id
In this PowerShell script, the
Start-Process
cmdlet starts the child script and stores its process object. The script waits for a keypress and then usesStop-Process
to terminate the child process.
Remember that forcefully terminating processes might lead to data loss or other issues, so use these methods carefully and only when necessary.