| 1 | package Ubic::Daemon::OS::POSIX; | ||
| 2 | $Ubic::Daemon::OS::POSIX::VERSION = '1.59'; | ||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | # ABSTRACT: POSIX-compatible daemonize helpers | ||
| 7 | |||
| 8 | use Params::Validate qw(:all); | ||
| 9 | use POSIX qw(:unistd_h); | ||
| 10 | |||
| 11 | use parent qw(Ubic::Daemon::OS); | ||
| 12 | |||
| 13 | sub pid2guid { | ||
| 14 | my ($self, $pid) = validate_pos(@_, 1, { type => SCALAR, regex => qr/^\d+$/ }); | ||
| 15 | |||
| 16 | return unless $self->pid_exists($pid); | ||
| 17 | |||
| 18 | return 'NULL'; # no guid on mac os x yet | ||
| 19 | } | ||
| 20 | |||
| 21 | sub pid2cmd { | ||
| 22 | my ($self, $pid) = validate_pos(@_, 1, { type => SCALAR, regex => qr/^\d+$/ }); | ||
| 23 | |||
| 24 | # see POSIX specification - http://pubs.opengroup.org/onlinepubs/009696799/utilities/ps.html | ||
| 25 | my $result = qx(ps -p $pid -o pid,comm 2>/dev/null); | ||
| 26 | $result =~ s/^.*\n//; # drop first line | ||
| 27 | my ($ps_pid, $ps_command) = $result =~ /^\s*(\d+)\s+(.*)$/; | ||
| 28 | unless ($ps_pid) { | ||
| 29 | warn "Daemon $pid not found"; | ||
| 30 | return 'unknown'; | ||
| 31 | } | ||
| 32 | unless ($ps_pid == $pid) { | ||
| 33 | die "Internal error, expected pid $pid, got pid $ps_pid"; | ||
| 34 | } | ||
| 35 | |||
| 36 | return $ps_command; | ||
| 37 | } | ||
| 38 | |||
| 39 | sub close_all_fh { | ||
| 40 | my ($self, @except) = @_; | ||
| 41 | |||
| 42 | for my $fd (0 .. POSIX::sysconf(POSIX::_SC_OPEN_MAX)) { | ||
| 43 | next if grep { $_ == $fd } @except; | ||
| 44 | POSIX::close($fd); | ||
| 45 | } | ||
| 46 | } | ||
| 47 | |||
| 48 | sub pid_exists { | ||
| 49 | my ($self, $pid) = validate_pos(@_, 1, { type => SCALAR, regex => qr/^\d+$/ }); | ||
| 50 | my $result = qx(ps -p $pid -o pid 2>/dev/null); | ||
| 51 | if ($result =~ /\d/) { | ||
| 52 | return 1; | ||
| 53 | } | ||
| 54 | return; | ||
| 55 | } | ||
| 56 | |||
| 57 | 1; | ||
| 58 | |||
| 59 | __END__ |