#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <dirent.h> #include <errno.h> #include <fcntl.h> #include <ctype.h> #include <string.h> #include <sys/ioctl.h> #include <sys/wait.h>
#define PROC_NAME "mymail" #define EXEC_NAME "/root/dev_mobile/source/MyMail/src/mymail" #define LOCKFILE "/root/mytest.lock" #define DEBUG int daemon_init() { struct sigaction act; int i, maxfd; int lock_fd; int ret; char buf[100]; lock_fd=open(LOCKFILE,O_RDWR|O_CREAT,0640); if(lock_fd<0){ printf("lockfile failed :\n"); exit(-1); } ret=flock(lock_fd,LOCK_EX|LOCK_NB);//因为下面关闭了,所以起不到作用 if(ret<0){ printf("can't obtaion the file lock:\n"); exit(0); } if (fork() != 0) exit(0); if (setsid() < 0) return -1; act.sa_handler = SIG_IGN; sigemptyset(&act.sa_mask); act.sa_flags = 0; sigaction(SIGHUP, &act, 0); if (fork() != 0) exit(0); chdir("/"); umask(0); setpgrp(); maxfd = sysconf(_SC_OPEN_MAX); for (i = 0; i < maxfd; i++) //close(i); ; sprintf(buf,"%6d\n",getpid()); write(lock_fd,buf,strlen(buf)); open("/dev/null", O_RDWR); dup(0); dup(1); dup(2); return 0; } static int file2str(char *filename, char *ret, int cap) { int fd, num_read;
if ((fd = open(filename, O_RDONLY, 0)) == -1) return -1; if ((num_read = read(fd, ret, cap - 1)) <= 0) return -1; ret[num_read] = 0; close(fd); return num_read; }
static int parse_proc_status(char*p_name,char *S) { char *tmp; unsigned char p_id[10]; memset(p_id, 0x00, sizeof(p_id)); sscanf(S, "Name:\t%15c", p_id); tmp = strchr(p_id, '\n'); if (tmp) *tmp = '\0'; //printf("%s\n",p_id); if(strcmp(p_name,p_id)==0) return 0; else return -1; return -1; }
static int proc_exist(char *p_name) { DIR *dir; FILE *file; struct dirent *entry; char path[32], sbuf[512]; int id; dir = opendir("/proc"); if (!dir){ perror("Can't open /proc"); exit(-1); } while ((entry = readdir(dir)) != NULL) { if (!isdigit(*entry->d_name)) continue; sprintf(path, "/proc/%s/status", entry->d_name); if ((file2str(path, sbuf, sizeof sbuf)) != -1) { if(parse_proc_status(p_name,sbuf)==0){ id=atol(entry->d_name); printf("id=%d\n",id); closedir(dir); return 0; } } } closedir(dir); return -1; }
static int proc_fork(char*p_path) { char * argv[ ]={PROC_NAME,(char*)0 }; pid_t pid; pid=fork(); if(pid==0){ execv(p_path,argv); } if(pid>0) printf("fork succeed:\n"); }
void handler() { char uidName[30]; char exec_path[50]; memset(uidName,0x00,sizeof(uidName)); memset(exec_path,0x00,sizeof(exec_path)); strcpy(uidName,PROC_NAME); strcpy(exec_path,EXEC_NAME); printf("one\n"); if (proc_exist(uidName)==0) printf("进程存在\n"); else proc_fork(exec_path); alarm(10); }
int main(int argc, char **argv) { #ifdef DEBUG if (daemon_init() < 0) { printf("daemon failed\n"); return 1; } #endif signal(SIGALRM,handler); alarm(15); while (1){ while ( waitpid(-1,NULL,WNOHANG) > 0) printf("test:\n"); } }
网上的unix比较多,前几天做了一个linux下的,监控某一程序,如果不存在,就启动。 |