-
Notifications
You must be signed in to change notification settings - Fork 24
feat: add ProcessSignaler to expose child process PIDs #160
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
wolfv
wants to merge
4
commits into
denoland:main
Choose a base branch
from
wolfv:process-signaler
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -57,6 +57,7 @@ pub struct ShellState { | |
| kill_signal: KillSignal, | ||
| process_tracker: ChildProcessTracker, | ||
| tree_exit_code_cell: TreeExitCodeCell, | ||
| process_signaler: ProcessSignaler, | ||
| } | ||
|
|
||
| impl ShellState { | ||
|
|
@@ -65,6 +66,25 @@ impl ShellState { | |
| cwd: PathBuf, | ||
| custom_commands: HashMap<String, Rc<dyn ShellCommand>>, | ||
| kill_signal: KillSignal, | ||
| ) -> Self { | ||
| Self::new_with_process_signaler( | ||
| env_vars, | ||
| cwd, | ||
| custom_commands, | ||
| kill_signal, | ||
| ProcessSignaler::new(), | ||
| ) | ||
| } | ||
|
|
||
| /// Creates a new ShellState with a custom ProcessSignaler. | ||
| /// | ||
| /// Use this when you need to track child process PIDs for signal forwarding. | ||
| pub fn new_with_process_signaler( | ||
| env_vars: HashMap<OsString, OsString>, | ||
| cwd: PathBuf, | ||
| custom_commands: HashMap<String, Rc<dyn ShellCommand>>, | ||
| kill_signal: KillSignal, | ||
| process_signaler: ProcessSignaler, | ||
| ) -> Self { | ||
| assert!(cwd.is_absolute()); | ||
| let mut commands = builtin_commands(); | ||
|
|
@@ -77,6 +97,7 @@ impl ShellState { | |
| kill_signal, | ||
| process_tracker: ChildProcessTracker::new(), | ||
| tree_exit_code_cell: Default::default(), | ||
| process_signaler, | ||
| }; | ||
| // ensure the data is normalized | ||
| for (name, value) in env_vars { | ||
|
|
@@ -169,6 +190,11 @@ impl ShellState { | |
| &self.kill_signal | ||
| } | ||
|
|
||
| /// Returns the process signaler for tracking child process PIDs. | ||
| pub fn process_signaler(&self) -> &ProcessSignaler { | ||
| &self.process_signaler | ||
| } | ||
|
|
||
| pub fn track_child_process(&self, child: &tokio::process::Child) { | ||
| self.process_tracker.track(child); | ||
| } | ||
|
|
@@ -632,6 +658,81 @@ impl KillSignalDropGuard { | |
| } | ||
| } | ||
|
|
||
| #[derive(Debug, Default)] | ||
| struct ProcessSignalerInner { | ||
| /// The PID of the current foreground process, if any. | ||
| current_pid: Cell<Option<u32>>, | ||
| /// Sender for process spawn notifications. | ||
| /// Lazily initialized on first subscribe. | ||
| sender: RefCell<Option<broadcast::Sender<u32>>>, | ||
| } | ||
|
|
||
| /// Provides access to the currently running foreground child process. | ||
| /// | ||
| /// This is useful for signal forwarding scenarios where you need to check | ||
| /// if the child process is in the same process group as the parent. | ||
| /// | ||
| /// # Example | ||
| /// | ||
| /// ```ignore | ||
| /// let signaler = ProcessSignaler::new(); | ||
| /// let mut receiver = signaler.subscribe(); | ||
| /// | ||
| /// // In a signal handler, check if we should forward the signal | ||
| /// if let Some(child_pid) = signaler.current_pid() { | ||
| /// // Check if child is in same process group | ||
| /// let child_pgid = unsafe { libc::getpgid(child_pid as i32) }; | ||
| /// let our_pgid = unsafe { libc::getpgid(0) }; | ||
| /// | ||
| /// if child_pgid != our_pgid { | ||
| /// // Child in different process group, forward signal | ||
| /// kill_signal.send(SignalKind::SIGINT); | ||
| /// } | ||
| /// } | ||
| /// ``` | ||
| #[derive(Debug, Clone, Default)] | ||
| pub struct ProcessSignaler(Rc<ProcessSignalerInner>); | ||
|
|
||
| impl ProcessSignaler { | ||
| /// Creates a new ProcessSignaler. | ||
| pub fn new() -> Self { | ||
| Self::default() | ||
| } | ||
|
|
||
| /// Returns the PID of the current foreground child process, if any. | ||
| /// | ||
| /// Returns `None` if no child process is currently running. | ||
| pub fn current_pid(&self) -> Option<u32> { | ||
|
||
| self.0.current_pid.get() | ||
| } | ||
|
|
||
| /// Subscribe to receive notifications when child processes spawn. | ||
| /// | ||
| /// Returns a receiver that yields PIDs of spawned processes. | ||
| /// The channel is lazily created on first subscription. | ||
| pub fn subscribe(&self) -> broadcast::Receiver<u32> { | ||
| let mut sender_ref = self.0.sender.borrow_mut(); | ||
| if sender_ref.is_none() { | ||
| let (sender, _) = broadcast::channel(16); | ||
| *sender_ref = Some(sender); | ||
| } | ||
| sender_ref.as_ref().unwrap().subscribe() | ||
| } | ||
|
|
||
| /// Called internally when a child process is spawned. | ||
| pub(crate) fn notify_spawn(&self, pid: u32) { | ||
| self.0.current_pid.set(Some(pid)); | ||
| if let Some(sender) = self.0.sender.borrow().as_ref() { | ||
| let _ = sender.send(pid); | ||
| } | ||
| } | ||
|
|
||
| /// Called internally when a child process exits. | ||
| pub(crate) fn notify_exit(&self) { | ||
| self.0.current_pid.set(None); | ||
| } | ||
| } | ||
|
|
||
| #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
| pub enum SignalKind { | ||
| SIGTERM, | ||
|
|
@@ -715,6 +816,7 @@ impl From<SignalKind> for i32 { | |
|
|
||
| #[cfg(test)] | ||
| mod test { | ||
| use super::ProcessSignaler; | ||
| use crate::KillSignal; | ||
| use crate::SignalKind; | ||
|
|
||
|
|
@@ -860,4 +962,79 @@ mod test { | |
| Some(SignalKind::SIGTERM.aborted_code()) | ||
| ); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_process_signaler_current_pid() { | ||
| let signaler = ProcessSignaler::new(); | ||
| assert_eq!(signaler.current_pid(), None); | ||
|
|
||
| signaler.notify_spawn(1234); | ||
| assert_eq!(signaler.current_pid(), Some(1234)); | ||
|
|
||
| signaler.notify_spawn(5678); | ||
| assert_eq!(signaler.current_pid(), Some(5678)); | ||
|
|
||
| signaler.notify_exit(); | ||
| assert_eq!(signaler.current_pid(), None); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_process_signaler_clone() { | ||
| let signaler = ProcessSignaler::new(); | ||
| let signaler_clone = signaler.clone(); | ||
|
|
||
| signaler.notify_spawn(1234); | ||
|
|
||
| // Both should see the same PID since they share the inner state | ||
| assert_eq!(signaler.current_pid(), Some(1234)); | ||
| assert_eq!(signaler_clone.current_pid(), Some(1234)); | ||
|
|
||
| signaler_clone.notify_exit(); | ||
| assert_eq!(signaler.current_pid(), None); | ||
| assert_eq!(signaler_clone.current_pid(), None); | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn test_process_signaler_subscribe() { | ||
| let signaler = ProcessSignaler::new(); | ||
| let mut receiver = signaler.subscribe(); | ||
|
|
||
| // Spawn notification should be received | ||
| signaler.notify_spawn(1234); | ||
|
|
||
| let pid = receiver.recv().await.unwrap(); | ||
| assert_eq!(pid, 1234); | ||
|
|
||
| // Multiple spawns should be received | ||
| signaler.notify_spawn(5678); | ||
| let pid2 = receiver.recv().await.unwrap(); | ||
| assert_eq!(pid2, 5678); | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn test_process_signaler_multiple_subscribers() { | ||
| let signaler = ProcessSignaler::new(); | ||
| let mut receiver1 = signaler.subscribe(); | ||
| let mut receiver2 = signaler.subscribe(); | ||
|
|
||
| signaler.notify_spawn(1234); | ||
|
|
||
| // Both receivers should get the notification | ||
| let pid1 = receiver1.recv().await.unwrap(); | ||
| let pid2 = receiver2.recv().await.unwrap(); | ||
| assert_eq!(pid1, 1234); | ||
| assert_eq!(pid2, 1234); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_process_signaler_no_subscribers() { | ||
| // Should not panic when there are no subscribers | ||
| let signaler = ProcessSignaler::new(); | ||
| signaler.notify_spawn(1234); | ||
| signaler.notify_exit(); | ||
|
|
||
| // PID should still be tracked even without subscribers | ||
| signaler.notify_spawn(5678); | ||
| assert_eq!(signaler.current_pid(), Some(5678)); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't think this would work because there could be multiple child processes running in different groups?