首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何终止从Shell启动的FS2流?

如何终止从Shell启动的FS2流?
EN

Stack Overflow用户
提问于 2021-02-25 16:16:40
回答 1查看 482关注 0票数 3

如果我从SBT shell运行这个程序,然后取消它,它将继续打印"hello“。我得离开SBT让它停下来。为什么会这样呢?

代码语言:javascript
复制
import cats.effect.{ExitCode, IO, IOApp}
import fs2.Stream
import scala.concurrent.duration._

object FS2 extends IOApp {

  override def run(args: List[String]) = 
      Stream.awakeEvery[IO](5.seconds).map { _ =>
        println("hello")
      }.compile.drain.as(ExitCode.Error)
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-07 00:13:48

正如注释中已经提到的,您的应用程序运行在另一个线程中,并且它永远不会终止,因为流是无限的,所以当应用程序接收到像SIGTERM或SIGINT这样的信号时,您必须手动终止它(每当您点击ctrl+c终止应用程序时,它就发出)。

你可以这样做:

  1. 创建递延
  2. 的实例,在接收到任何术语或INT信号后,使用它触发interruptWhen

例如:

代码语言:javascript
复制
import sun.misc.Signal

object FS2 extends IOApp {

  override def run(args: List[String]): IO[ExitCode] = for {
    cancel <- Deferred[IO, Either[Throwable, Unit]] //deferred used as flat telling if terminations signal
                                                    //was received
    _ <- (IO.async_[Unit]{ cb =>
      Signal.handle(
        new Signal("INT"), //INT and TERM signals are nearly identical, we have to handle both
        (sig: Signal) => cb(Right(()))
      )
      Signal.handle(
        new Signal("TERM"),
        (sig: Signal) => cb(Right(()))
      )
    } *> cancel.complete(Right(()))).start //after INT or TERM signal is intercepted it will complete
                                           //deferred and terminate fiber
                                           //we have to run method start to run waiting for signal in another fiber
                                           //in other case program will block here
    app <- Stream.awakeEvery[IO](1.seconds).map { _ => //your stream
      println("hello")
    }.interruptWhen(cancel).compile.drain.as(ExitCode.Error)  //interruptWhen ends stream when deferred completes
  } yield app

}

当您在shell中单击ctrl + c时,此版本的应用程序将终止。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66372308

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档