File Coverage

File:Dpkg/Exit.pm
Coverage:95.3%

linestmtbrancondsubpodtimecode
1# Copyright © 2002 Adam Heath <doogie@debian.org>
2# Copyright © 2012-2013 Guillem Jover <guillem@debian.org>
3#
4# This program is free software; you can redistribute it and/or modify
5# it under the terms of the GNU General Public License as published by
6# the Free Software Foundation; either version 2 of the License, or
7# (at your option) any later version.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12# GNU General Public License for more details.
13#
14# You should have received a copy of the GNU General Public License
15# along with this program.  If not, see <https://www.gnu.org/licenses/>.
16
17package Dpkg::Exit;
18
19
1
1
1
2
1
12
use strict;
20
1
1
1
1
0
31
use warnings;
21
22our $VERSION = '2.00';
23our @EXPORT_OK = qw(
24    push_exit_handler
25    pop_exit_handler
26    run_exit_handlers
27);
28
29
1
1
1
1
1
131
use Exporter qw(import);
30
31my @handlers = ();
32
33=encoding utf8
34
35 - 51
=head1 NAME

Dpkg::Exit - program exit handlers

=head1 DESCRIPTION

The Dpkg::Exit module provides support functions to run handlers on exit.

=head1 FUNCTIONS

=over 4

=item push_exit_handler($func)

Register a code reference into the exit function handlers stack.

=cut
52
53sub push_exit_handler {
54
5
1
3
    my ($func) = shift;
55
56
5
6
    _setup_exit_handlers() if @handlers == 0;
57
5
4
    push @handlers, $func;
58}
59
60 - 64
=item pop_exit_handler()

Pop the last registered exit handler from the handlers stack.

=cut
65
66sub pop_exit_handler {
67
1
1
2
    _reset_exit_handlers() if @handlers == 1;
68
1
1
    pop @handlers;
69}
70
71 - 75
=item run_exit_handlers()

Run the registered exit handlers.

=cut
76
77sub run_exit_handlers {
78
5
1
6
    while (my $handler = pop @handlers) {
79
4
101
        $handler->();
80    }
81
4
104
    _reset_exit_handlers();
82}
83
84sub _exit_handler {
85
1
2
    run_exit_handlers();
86
0
0
    exit(127);
87}
88
89my @SIGNAMES = qw(INT HUP QUIT);
90my %SIGOLD;
91
92sub _setup_exit_handlers
93{
94
3
6
    foreach my $signame (@SIGNAMES) {
95
9
10
        $SIGOLD{$signame} = $SIG{$signame};
96
9
24
        $SIG{$signame} = \&_exit_handler;
97    }
98}
99
100sub _reset_exit_handlers
101{
102
5
3
    foreach my $signame (@SIGNAMES) {
103
15
60
        $SIG{$signame} = $SIGOLD{$signame};
104    }
105}
106
107END {
108
1
164
    local $?;
109
1
1
    run_exit_handlers();
110}
111
112=back
113
114 - 130
=head1 CHANGES

=head2 Version 2.00 (dpkg 1.20.0)

Hide variable: @handlers.

=head2 Version 1.01 (dpkg 1.17.2)

New functions: push_exit_handler(), pop_exit_handler(), run_exit_handlers()

Deprecated variable: @handlers

=head2 Version 1.00 (dpkg 1.15.6)

Mark the module as public.

=cut
131
1321;