#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#define SYNC_LOCK "/usr/local/nagios/var/rw/nagioslogd.pid"
#define SYNC_LOCK_A "/usr/local/nagios/var/rw/nagioslogd.ctx"
static char nagios_lock[100] = "/usr/local/nagios/var/rw/nagioslogd.pid";
int check_pid (char *pidfile) {
int pid = read_pid (pidfile);
if ((!pid) || (pid == getpid ())) {
return 0;
}
if (kill (pid, 0) && errno == ESRCH) {
return (0);
}
return pid;
}
int read_pid (char *pidfile) {
FILE *f;
int pid;
if (!(f = fopen (pidfile, "r")))
return 0;
fscanf (f, "%d", &pid);
fclose (f);
return pid;
}
static int create_lock (void) {
int fd = open (nagios_lock, O_WRONLY | O_CREAT | O_EXCL | O_TRUNC);
if (fd < 0) {
if (errno == EEXIST) {
fprintf (stderr, "nagios: lock file /"%s/" already exists/n",
nagios_lock);
exit (0);
} else {
fprintf (stderr,
"nagios: unable to create lock file /"%s/" (%d %s)/n",
nagios_lock, errno, strerror (errno));
exit (0);
}
}
return fd;
}
static int fill_lock (int lockfd, pid_t pid) {
char buf[30];
int len = snprintf (buf, sizeof (buf), "%u/n", (unsigned int) pid);
int ok = len > 0 && write (lockfd, buf, len) == len;
close (lockfd);
return ok;
}
int main ( )
{
if (check_pid (SYNC_LOCK) == 1) {
fprintf (stderr, "nagioslogd is running now OK /n");
} else {
fprintf (stderr, "nagioslogd is not running now ERROR /n");
}
if (check_pid (SYNC_LOCK) == 0)
{
printf ("delete .........../n");
unlink (SYNC_LOCK);
unlink (SYNC_LOCK_A);
};
int lockfd = create_lock ();
int pid = fork ();
if ( pid != 0)
{
exit (fill_lock (lockfd, pid));
}
sleep (50);
}