]>
git.ipfire.org Git - people/stevee/guardian.git/blob - modules/Daemon.pm
1 package Guardian
::Daemon
;
6 use Exporter
qw(import);
8 our @EXPORT_OK = qw(Daemonize IsRunning GetPID WritePID RemovePIDFile);
10 # The file and path where the pidfile which contains the PID (process id)
11 # of guardian when running in daemon mode will be written.
12 my $pidfile = "/run/guardian/guardian.pid";
13 my $pid_path = "/run/guardian";
16 ## The main function to daemonize guardian.
18 ## When this function is called, the running guardian process will be forked
19 ## into the background and become a daemon.
22 # Setting the session identifier to the current process.
23 &POSIX
::setsid
or die "Could not set session identifer (setsid): $!";
25 # Fork into the background.
28 # Check if we forked successfully.
30 die "Could not fork into background: $!";
32 # Clean exit the parent process.
37 # Change working directory.
43 # Set max number of "open" descriptors to system default, if not set
45 foreach (0 .. (POSIX
::sysconf
(&POSIX
::_SC_OPEN_MAX
) || 1024))
47 # This function does not require any input, so close it.
50 # Open new I/O streams.
51 open (STDIN
, "</dev/null");
52 open (STDOUT
, ">/dev/null");
53 open (STDERR
, ">&STDOUT");
55 # Call sub to write out the process id.
62 ## This function will write the current process id to guardians PID file. If the path to
63 ## does not exist yet, it automatically will be created.
66 # Create directory for storing the pidfile if it does not exist yet.
67 unless (-d
"$pid_path") {
72 open(PIDFILE
, ">$pidfile") or die "Could not write $pidfile. $!\n";
74 # Write process-id to the pidfile.
84 ## This subfunction provides an easy to use mechanism to the the process id (PID)
85 ## from the pidfile of guardian.
88 # Check if the pidfile exists.
89 unless (-r
"$pidfile") {
94 open(PIDFILE
, "<$pidfile") or die "Could not open $pidfile: $!\n";
96 # Read the process id.
99 # Close the file afterwards.
102 # Check if we got a valid process id.
103 unless ($pid =~ /^(\d+)$/ ) {
107 # Return the process id.
112 ## Function IsRunning.
114 ## A subfunction to check if a process by a given process id (PID) is running or not.
120 # If we got no process id, no instance of guardian is running yet.
125 # Check if the process exists or not by sending a test signal to the process id.
126 my $is_running = kill(0, $pid);
128 # Return true if the process is running.
133 # If we got here, there is not process running which uses the given id or something
134 # went wrong. Return undef (False) in this case.
139 ## RemovePIDFile function.
141 ## This very tiny function just removes an existing PID file.
143 sub RemovePIDFile
() {
144 # Check if a socketfile exists.
146 # Delete the pid file.