- pid文件管理
#include <stdio.h>
#include <sys/file.h>
#include <unistd.h>
#include <errno.h>
#include <cstdio>
#define PID_FILE "./pid"
int main() {
FILE *fp = NULL;
if ((fp = fopen(PID_FILE, "w+")) == NULL) {
printf("pid file open error, errno=%d\n", errno);
return -1;
}
if(flock(fp->_fileno, LOCK_EX | LOCK_NB) != 0) {
printf("program is running\n");
return -1;
}
int pid = (int)getpid();
printf("program pid:%d\n", pid);
if (fwrite(fp, "%d\n", pid) <= 0) {
printf("write pid fail, errno:%d\n", errno);
}
fflush(fp);
while (true) {
sleep(1);
}
fclose(fp);
return 0;
}
stop pid文件写入的进程:
#! /bin/sh
cat pid | xargs kill -9 &>/dev/null && echo "stopped"
- 监控子进程是否运行正常的代码:
while (1)
{
if (waitpid(pid, NULL, WNOHANG))//判断子进程是否运行正常
{
pid = ForkWorker();
if (pid < 0)
{
ERROR_LOG("master_monitoragent: failed to refork worker_monitoragent!");
}
else if (pid > 0)
{
INFO_LOG("master_monitoragent: success to refork worker_monitoragent!");
}
}
sleep(5);
}