#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <string>
#include <algorithm>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/sem.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <pthread.h>
#include <semaphore.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <dirent.h>
using namespace std;
#define WAIT_TIME_OUT 3
//根据进程名称获取进程id,然后根据进程id关闭进程
//ProcName:进程名称
int close_pid_by_name(string ProcName)
{
DIR *dir; // 目录
struct dirent *d; // 目录结构体
pid_t pid; // 进程id
char *s;
string strpath, strpname;
int pnlen, status;
pnlen = ProcName.length();
/* Open the /proc directory. */
dir = opendir("/proc");
if (!dir)
{
return -1;
}
// 遍历"/proc"目录
while ((d = readdir(dir)) != NULL) {
char exe[PATH_MAX + 1];
char path[PATH_MAX + 1];
int len;
int namelen;
// 判断是否是进程,每个进程按进程号分配文件夹
if ((pid = atoi(d->d_name)) == 0)
continue;
snprintf(exe, sizeof(exe), "/proc/%s/exe", d->d_name);
if ((len = readlink(exe, path, PATH_MAX)) < 0)
continue;
path[len] = '\0';
// 获取进程名称
s = strrchr(path, '/');
if (s == NULL)
continue;
s++;
strpname = s;
// 进程名称匹配则杀死该进程
namelen = strlen(s);
if (namelen < pnlen)
continue;
if (strpname.find(ProcName) != strpname.npos)
{
kill(pid, SIGKILL);
}
}
closedir(dir);
return 0;
}
void daemon(string pname)
{
// 创建信号量
sem_t* psem = sem_open("/Name_Semphore", O_CREAT | O_RDONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP, 1);
if (psem == SEM_FAILED)
{
return;
}
while (true)
{
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec = ts.tv_sec + WAIT_TIME_OUT;
int result1 = sem_timedwait(psem, &ts);
if (result1 == -1)
{
ts.tv_sec = ts.tv_sec + WAIT_TIME_OUT;
int result2 = sem_timedwait(psem, &ts);
if (result2 == -1)
{
close_pid_by_name(pname);
break;
}
}
usleep(1000);
}
return;
}
int main(int argc, char* argv[])
{
if (argc != 2)
{
printf("paras err\n");
return -1;
}
// 被守护进程的名
std::string process_name = argv[1];
pid_t pid;
int i, fd;
pid = fork(); // 第一步,创建新进程
if (pid < 0)
{
printf("fork err\n");// fork失败
exit(1);
}
else if (pid > 0)
{
printf("main quit\n");// 主进程直接退出
exit(0);
}
else // 这里是守护进程的内容
{
printf("daemon\n");
setsid(); //第二步,设置新的会话
chdir("/tmp"); //第三步,改变工作路径
umask(0); //第四步,改变掩码
//第五步 关闭所有描述符,(输出信息可以记录在系统日志,/var/log/syslog)
int max_fd = sysconf(_SC_OPEN_MAX);
for (i = 0;i < max_fd;i++)
close(i);
daemon(process_name);
}
}