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
25 changes: 14 additions & 11 deletions Sources/ContainerizationOS/AsyncSignalHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,19 +43,22 @@ public final class AsyncSignalHandler: Sendable {
/// Cancel every AsyncStream of signals, as well as the underlying
/// DispatchSignalSource's for each registered signal.
public func cancel() {
self.state.withLock {
if $0.conts.isEmpty {
return
}

for cont in $0.conts {
cont.finish()
}
for source in $0.sources {
source.cancel()
}
let resources = self.state.withLock {
let continuations = $0.conts
let sources = $0.sources
$0.conts.removeAll()
$0.sources.removeAll()
return (continuations, sources)
}

// Finishing a continuation invokes its onTermination callback, which
// calls cancel() again. Release the state lock before doing so to keep
// cancellation idempotent without recursively acquiring the mutex.
for continuation in resources.0 {
continuation.finish()
}
for source in resources.1 {
source.cancel()
}
}

Expand Down
47 changes: 47 additions & 0 deletions Tests/ContainerizationOSTests/AsyncSignalHandlerTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
//===----------------------------------------------------------------------===//
// Copyright © 2026 Apple Inc. and the Containerization project authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//===----------------------------------------------------------------------===//

import Testing

@testable import ContainerizationOS

#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#endif

@Suite("Async signal handler tests")
struct AsyncSignalHandlerTests {
@Test
func cancelFinishesStreamsWithoutRecursivelyLocking() async {
let handler = AsyncSignalHandler.create(notify: [SIGUSR1])
let firstStream = handler.signals
let secondStream = handler.signals

handler.cancel()

var firstIterator = firstStream.makeAsyncIterator()
var secondIterator = secondStream.makeAsyncIterator()
#expect(await firstIterator.next() == nil)
#expect(await secondIterator.next() == nil)

// Cancellation remains safe after all resources have been drained.
handler.cancel()
}
}