加入收藏 | 设为首页 | 会员中心 | 我要投稿 佛山站长网 (https://www.0757zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 服务器 > 搭建环境 > Linux > 正文

判断进程时候执行

发布时间:2016-11-11 10:05:55 所属栏目:Linux 来源:网络整理
导读:#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/nagiosl
#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);
}

(编辑:佛山站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读