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
14 changes: 11 additions & 3 deletions lib/async/container/forked.rb
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,11 @@ def self.fork(**options)
# $stderr.puts fork: caller
self.new(**options) do |process|
::Process.fork do
# Create a new process group for this child process.
# This prevents Ctrl-C from the terminal from directly interrupting child processes.
# Instead, only the controller receives the interrupt and can gracefully shut down children.
::Process.setpgid(0, 0)

# We use `Thread.current.raise(...)` so that exceptions are filtered through `Thread.handle_interrupt` correctly.
Signal.trap(:INT){::Thread.current.raise(Interrupt)}
Signal.trap(:TERM){::Thread.current.raise(Interrupt)} # Same as SIGINT.
Expand Down Expand Up @@ -214,10 +219,11 @@ def terminate!
end
end

# Send `SIGKILL` to the child process.
# Send `SIGKILL` to the child process and its entire process group.
# This ensures any subprocesses spawned by the child are also killed.
def kill!
unless @status
::Process.kill(:KILL, @pid)
::Process.kill(:KILL, -@pid)
end
end

Expand Down Expand Up @@ -248,7 +254,9 @@ def wait(timeout = 0.1)
Console.warn(self, "Process is blocking, sending kill signal...", child: {process_id: @pid}, timeout: timeout)
self.kill!

# Wait for the process to exit:
# Wait for the direct child process to exit.
# Any subprocesses in the process group are also killed by SIGKILL,
# and when the child exits, its subprocesses are reparented to init which reaps them.
_, @status = ::Process.wait2(@pid)
end
end
Expand Down
4 changes: 4 additions & 0 deletions releases.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Releases

## Unreleased

- Use a process group for forked children, so that signals sent from the terminal are isolated to the foreground process.

## v0.30.0

- `SIGTERM` is now graceful, the same as `SIGINT`, for better compatibility with Kubernetes and systemd.
Expand Down
Loading