Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package kyo.internal

import OsSignal.Handler
import scala.scalanative.posix.signal as posix
import scala.scalanative.unsafe.*

/** Internal global dispatcher to avoid capturing local state in C callbacks. */
private object NativeSignalDispatch:
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is to get around CFuncPtr.fromScalaFunction introducing undefined behavior when capturing lambdas. Not sure about the correctness.

private val registry = scala.collection.mutable.HashMap.empty[Int, () => Unit]

val cHandler: CFuncPtr1[CInt, Unit] = CFuncPtr1.fromScalaFunction { (sig: CInt) =>
val cb = registry.synchronized { registry.get(sig) }
cb.foreach(_.apply())
}

def install(signum: CInt, cb: () => Unit): Unit =
registry.synchronized { registry.update(signum, cb) }
end NativeSignalDispatch

/** Native-specific implementation using POSIX signals via Scala Native. */
private[internal] class OsSignalPlatformSpecific:
val handle: Handler = new Handler:
private def signum(signal: String): CInt =
signal match
case "INT" => posix.SIGINT
case "TERM" => posix.SIGTERM
case "HUP" => posix.SIGHUP

override def apply(signalName: String, handler: () => Unit): Unit =
val num = signum(signalName)
NativeSignalDispatch.install(num, handler)
val _ = posix.signal(num, NativeSignalDispatch.cHandler)
end apply
end OsSignalPlatformSpecific
Loading