我正在使用 golang 启动进程并监视输出。该进程将运行很长时间,我需要能够发送信号来结束它。
我有以下代码,在大多数情况下运行良好。但由于某些原因,进程可能没有输出,for循环会被scan()
方法阻塞,无法接收来自processfinishchan
的消息。
是否有一种简单的方法可以为 scan()
方法设置超时?我尝试了一个解决方案,在另一个 goroutine 中运行 scan()
,并使用另一个 select 从新的 goroutine 和超时通道接收,但考虑到外部 for
循环,是否会有越来越多的 goroutine 被 scan
阻塞? p>
// code that start the process... scanner := bufio.NewScanner(stdout) for { select { case <-processFinishChan: // send to this channel to terminate the process log.Println("Killing Process") err := cmdObject.Process.Kill() if err != nil { log.Printf("Error Killing: %v", err) } else { return } default: // default case, read the output of process and send to user. if !scanner.Scan() && scanner.Err() == nil { // reach EOF return } m := scanner.Bytes() WSOutChanHolder.mu.Lock() for _, ch := range WSOutChanHolder.data { ch <- m } WSOutChanHolder.mu.Unlock() } }
正确答案
假设 stdout
是 cmdobject.stdoutpipe()
的结果,则读取器应在进程退出后等待时关闭读取器并中断任何正在进行的读取。
wait 将在看到命令退出后关闭管道,因此大多数调用者不需要自己关闭管道。
所以,我们需要在一个单独的goroutine中杀死该进程,然后在杀死该进程后等待观察它的发生并关闭阅读器。
// code that start the process... scanner := bufio.NewScanner(stdout) go func() { <-processFinishChan: // send to this channel to terminate the process log.Println("Killing Process") err := cmdObject.Process.Kill() if err != nil { log.Printf("Error Killing: %v", err) } cmdObject.Wait() } () for { // default case, read the output of process and send to user. if !scanner.Scan() && scanner.Err() == nil { // reach EOF return } m := scanner.Bytes() WSOutChanHolder.mu.Lock() for _, ch := range WSOutChanHolder.data { ch <- m } WSOutChanHolder.mu.Unlock() }
以上是如何为循环扫描的bufio扫描仪设置超时?的详细内容。更多信息请关注PHP中文网其他相关文章!

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建筑物内currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用辅助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization

CustomInterfacesingoarecrucialforwritingFlexible,可维护,andTestableCode.TheyEnableDevelostOverostOcusonBehaviorBeiroveration,增强ModularityAndRobustness.byDefiningMethodSigntulSignatulSigntulSignTypaterSignTyperesthattypesmustemmustemmustemmustemplement,InterfaceSallowForCodeRepodEreusaperia

使用接口进行模拟和测试的原因是:接口允许定义合同而不指定实现方式,使得测试更加隔离和易于维护。1)接口的隐式实现使创建模拟对象变得简单,这些对象在测试中可以替代真实实现。2)使用接口可以轻松地在单元测试中替换服务的真实实现,降低测试复杂性和时间。3)接口提供的灵活性使得可以为不同测试用例更改模拟行为。4)接口有助于从一开始就设计可测试的代码,提高代码的模块化和可维护性。

在Go中,init函数用于包初始化。1)init函数在包初始化时自动调用,适用于初始化全局变量、设置连接和加载配置文件。2)可以有多个init函数,按文件顺序执行。3)使用时需考虑执行顺序、测试难度和性能影响。4)建议减少副作用、使用依赖注入和延迟初始化以优化init函数的使用。

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,执行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,确保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,确保Allimizegoroutines,确保AllizeNizeGoROutines,确保AllimizeGoroutines


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境