diff options
author | Eric Wong <e@80x24.org> | 2024-04-01 06:49:37 +0000 |
---|---|---|
committer | Eric Wong <e@80x24.org> | 2024-04-03 08:28:05 +0000 |
commit | 108196adad5e70b6dd40dc431cd1033d44679483 (patch) | |
tree | 6c9f2761263a5f188ef47d58b5c652a8f7ab2497 /lib/PublicInbox/OnDestroy.pm | |
parent | 9aba037ad27f1ec8e9c37580d23ea7a8944e8ae5 (diff) | |
download | public-inbox-108196adad5e70b6dd40dc431cd1033d44679483.tar.gz |
getpid() isn't cached by glibc nowadays and system calls are more expensive due to CPU vulnerability mitigations. To ensure we switch to the new semantics properly, introduce a new `on_destroy' function to simplify callers. Furthermore, most OnDestroy correctness is often tied to the process which creates it, so make the new API default to guarded against running in subprocesses. For cases which require running in all children, a new PublicInbox::OnDestroy::all call is provided.
Diffstat (limited to 'lib/PublicInbox/OnDestroy.pm')
-rw-r--r-- | lib/PublicInbox/OnDestroy.pm | 27 |
1 files changed, 17 insertions, 10 deletions
diff --git a/lib/PublicInbox/OnDestroy.pm b/lib/PublicInbox/OnDestroy.pm index d9a6cd24..4301edff 100644 --- a/lib/PublicInbox/OnDestroy.pm +++ b/lib/PublicInbox/OnDestroy.pm @@ -3,22 +3,29 @@ package PublicInbox::OnDestroy; use v5.12; +use parent qw(Exporter); +use autodie qw(fork); +our @EXPORT = qw(on_destroy); +our $fork_gen = 0; -sub new { - shift; # ($class, $cb, @args) - bless [ @_ ], __PACKAGE__; +# either parent or child is expected to exit or exec shortly after this: +sub fork_tmp () { + my $pid = fork; + ++$fork_gen if $pid == 0; + $pid; } +# all children +sub all (@) { bless [ undef, @_ ], __PACKAGE__ } + +# same process +sub on_destroy (@) { bless [ $fork_gen, @_ ], __PACKAGE__ } + sub cancel { @{$_[0]} = () } sub DESTROY { - my ($cb, @args) = @{$_[0]}; - if (!ref($cb) && $cb) { - my $pid = $cb; - return if $pid != $$; - $cb = shift @args; - } - $cb->(@args) if $cb; + my ($fgen, $cb, @args) = @{$_[0]}; + $cb->(@args) if ($cb && ($fgen // $fork_gen) == $fork_gen); } 1; |