blib/lib/Ubic/Daemon/OS/Linux.pm untested

filter: Statementstmt 0.0% 0 / 52 Branchbran 0.0% 0 / 12 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 0.0% 0 / 8 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 76 SCAR 40.3
CC
7
Cov
0%
pid2guid
20.0
pid2cmd
12.0
close_all_fh
6.0
CRAP 56.0
1 package Ubic::Daemon::OS::Linux;
2 $Ubic::Daemon::OS::Linux::VERSION = '1.59';
3 use strict;
4 use warnings;
5  
6 # ABSTRACT: linux-specific daemonize helpers
7  
8  
9 use POSIX;
10  
11 use parent qw(Ubic::Daemon::OS);
12  
13 sub pid2guid {
14 my ($self, $pid) = @_;
15  
16 unless (-d "/proc/$pid") {
17 return; # process not found
18 }
19 my $opened = open(my $fh, '<', "/proc/$pid/stat");
20 unless ($opened) {
21 # open failed
22 my $error = $!;
23 unless (-d "/proc/$pid") {
24 return; # process exited right now
25 }
26 die "Open /proc/$pid/stat failed: $!";
27 }
28 my $line = <$fh>;
29 # cut first two fields (pid and process name)
30 # since process name can contain spaces, we can't just split line by \s+
31 $line =~ s/^\d+\s+\([^)]*\)\s+//;
32  
33 my @fields = split /\s+/, $line;
34 my $guid = $fields[19];
35 return $guid;
36 }
37  
38 sub pid2cmd {
39 my ($self, $pid) = @_;
40  
41 my $daemon_cmd_fh;
42 unless (open $daemon_cmd_fh, '<', "/proc/$pid/cmdline") {
43 # this can happen if pid got reused and now it belongs to the kernel process, e.g., [kthreadd]
44 warn "Can't open daemon's cmdline: $!";
45 return 'unknown';
46 }
47 my $daemon_cmd = <$daemon_cmd_fh>;
48 unless ($daemon_cmd) {
49 # strange, open succeeded but file is empty
50 # this can happen, though, for example if pid belongs to the kernel thread
51 warn "Can't read daemon cmdline";
52 return 'unknown';
53 }
54 $daemon_cmd =~ s/\x{00}$//;
55 $daemon_cmd =~ s/\x{00}/ /g;
56 close $daemon_cmd_fh;
57  
58 return $daemon_cmd;
59 }
60  
61 sub close_all_fh {
62 my ($self, @except) = @_;
63  
64 my @fd_nums = map { s!^.*/!!; $_ } glob("/proc/$$/fd/*");
65 for my $fd (@fd_nums) {
66 next if grep { $_ == $fd } @except;
67 POSIX::close($fd);
68 }
69 }
70  
71 sub pid_exists {
72 my ($self, $pid) = @_;
73 return (-d "/proc/$pid");
74 }
75  
76 1;
77  
78 __END__