【问题标题】:kill child processes when parent ends父进程结束时杀死子进程
【发布时间】:2019-12-06 09:27:47
【问题描述】:

我的目标是杀死(或以某种方式优雅地关闭)由 powershell 脚本启动的子进程,以便在父进程死亡后不会继续运行(通常通过点击脚本结尾或通过崩溃或 ctrl+c 或任何其他方式)。

我尝试了几种方法,但都没有达到预期效果:

# only one line was active at time, all other were commented
start-job -scriptblock { & 'notepad.exe' }    # notepad.exe started, script continues to end, notepad.exe keep running
start-job -scriptblock { 'notepad.exe' }      # notepad.exe not started, script continues to end
notepad.exe                                   # notepad.exe started, script continues to end, notepad.exe keep running
& notepad.exe                                 # notepad.exe started, script continues to end, notepad.exe keep running
start-Process -passthru -FilePath notepad.exe # notepad.exe started, script continues to end, notepad.exe keep running

# give script some time before ending
Write-Host "Begin of sleep section"
Start-Sleep -Seconds 5
Write-Host "End of sleep section"

【问题讨论】:

    标签: powershell process kill spawn resource-cleanup


    【解决方案1】:

    您可以通过finally clause 处理这种事情。 finally 子句在 try 块之后执行,即使 try 块的执行引发了异常或执行被用户中止。

    因此,解决您的问题的一种方法如下:

    1. 跟踪子进程的进程 ID,您的脚本正在生成和

    2. 在 finally 子句中杀死这些进程。

        try
        {
           $process = Start-Process 'notepad.exe' -PassThru 
    
           # give script some time before ending
            Write-Host "Begin of sleep section"
            Start-Sleep -Seconds 5
            Write-Host "End of sleep section"
    
        }
        finally
        {
            # Kill the process if it still exists after the script ends.
            # This throws an exception, if process ended before the script.
            Stop-Process -Id $process.Id
        }
    
    

    【讨论】:

    • 非常感谢。接受并投票赞成。有没有最后没有赶上脚本结尾的情况?
    • 有。如果你杀死整个运行脚本的powershell.exe 进程,finally 将没有机会。