判斷進程時候執行。

#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);
}

發佈了67 篇原創文章 · 獲贊 13 · 訪問量 39萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章