当前位置:网站首页>[Sylar] framework -chapter20- daemon module
[Sylar] framework -chapter20- daemon module
2022-07-28 04:33:00 【Jianghu people call it pineapple bag】
Standing on the shoulders of giants
Rewrite from scratch sylar C++ High performance distributed server framework
summary
- Unbind the process from the terminal , Go to the background and run ( adopt fork The sub process is implemented as the main business process ).
- sylar Realize the dual process wake-up function , When the parent process acts as a daemon, it will detect whether the child process exits , If the subprocess exits , Will periodically restart the subprocess .
daemon.h
- ProcessInfo
- The singleton pattern , Store some information about the required process .
- start_daemon
- External interface .
Other instructions
- The following are the implementation steps of the daemon :
- call daemon(1, 0) Run the current process as a daemon ;
- Daemon fork Subprocesses , Run the main business in the sub process ;
- Parent process passed waitpid() Check whether the subprocess exits , If the subprocess exits , Then pull up the subprocess again .
- daemon() function
#include <unistd.h> int daemon(int nochdir, int noclose);- When nochdir by 0 when ,daemon Change the working directory of the process to the root directory root(“/”).
- When noclose by 0 when ,daemon Will the process of STDIN, STDOUT, STDERR All redirected to /dev/null, That is, no information is output , Otherwise, output . In general , This parameter is set to 0 Of .
- deamon() Called fork(), If fork success , The parent process is in daemon Kill yourself after the function runs , The subprocess consists of init Process adoption . The subprocess at this time , It's actually a daemon .
- In general use daemon(1, 0);
Some related codes
/**
* @filename daemon.h
* @brief Daemon module
* @author L-ge
* @version 0.1
* @modify 2022-07-18
*/
#ifndef __SYLAR_DAEMON_H__
#define __SYLAR_DAEMON_H__
#include <unistd.h>
#include <functional>
#include "sylar/singleton.h"
namespace sylar
{
struct ProcessInfo
{
/// The parent process id
pid_t parent_id = 0;
/// The main process id
pid_t main_id = 0;
/// Parent process start time
uint64_t parent_start_time = 0;
/// Main process start time
uint64_t main_start_time = 0;
/// The number of times the main process is restarted
uint32_t restart_count = 0;
std::string toString() const;
};
typedef sylar::Singleton<ProcessInfo> ProcessInfoMgr;
/**
* @brief The startup program can choose to use the way of daemon
* @param[in] argc Number of parameters
* @param[in] argv Parameter value array
* @param[in] main_cb Start the function
* @param[in] is_daemon Whether the way of daemon
* @return Return the execution result of the program
*/
int start_daemon(int argc, char** argv
, std::function<int(int argc, char** argv)> main_cb
, bool is_daemon);
}
#endif
#include "daemon.h"
#include "sylar/log.h"
#include "sylar/config.h"
#include <time.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
namespace sylar
{
static sylar::Logger::ptr g_logger = SYLAR_LOG_NAME("system");
static sylar::ConfigVar<uint32_t>::ptr g_daemon_restart_interval
= sylar::Config::Lookup("daemon.restart_interval", (uint32_t)5, "daemon restart interval");
std::string ProcessInfo::toString() const
{
std::stringstream ss;
ss << "[ProcessInfo parent_id=" << parent_id
<< " main_id=" << main_id
<< " parent_start_time=" << sylar::Time2Str(parent_start_time)
<< " main_start_time=" << sylar::Time2Str(main_start_time)
<< " restart_count=" << restart_count << "]";
return ss.str();
}
static int real_start(int argc, char** argv,
std::function<int(int argc, char** argv)> main_cb)
{
ProcessInfoMgr::GetInstance()->main_id = getpid();
ProcessInfoMgr::GetInstance()->main_start_time = time(0);
return main_cb(argc, argv);
}
static int real_daemon(int argc, char** argv,
std::function<int(int argc, char** argv)> main_cb)
{
// #include <unistd.h>
// int daemon(int nochdir, int noclose);
// When nochdir by 0 when ,daemon Change the working directory of the process to the root directory root("/").
// When noclose by 0 when ,daemon Will the process of STDIN, STDOUT, STDERR All redirected to /dev/null, That is, no information is output , Otherwise, output . In general , This parameter is set to 0 Of .
// deamon() Called fork(), If fork success , The parent process is in daemon Kill yourself after the function runs , The subprocess consists of init Process adoption . The subprocess at this time , It's actually a daemon .
daemon(1, 0); // Create daemons
ProcessInfoMgr::GetInstance()->parent_id = getpid();
ProcessInfoMgr::GetInstance()->parent_start_time = time(0);
while(true)
{
pid_t pid = fork();
if(pid == 0)
{
// Subprocess return
ProcessInfoMgr::GetInstance()->main_id = getpid();
ProcessInfoMgr::GetInstance()->main_start_time = time(0);
SYLAR_LOG_INFO(g_logger) << "process start pid=" << getpid();
return real_start(argc, argv, main_cb);
}
else if(pid < 0)
{
SYLAR_LOG_ERROR(g_logger) << "fork fail return=" << pid
<< " errno=" << errno << " errstr=" << strerror(errno);
return -1;
}
else
{
// The parent process returns
int status = 0;
waitpid(pid, &status, 0);
if(status)
{
if(status == 9)
{
SYLAR_LOG_INFO(g_logger) << "killed";
break;
}
else
{
SYLAR_LOG_ERROR(g_logger) << "child crash pid=" << pid
<< " status=" << status;
}
}
else
{
SYLAR_LOG_INFO(g_logger) << "child finished pid=" << pid;
break;
}
ProcessInfoMgr::GetInstance()->restart_count += 1;
// Prevent the resources from being fully recycled after the child process dies ,
// At this time and immediately fork There may be problems with child processes .
sleep(g_daemon_restart_interval->getValue());
}
}
return 0;
}
int start_daemon(int argc, char** argv
, std::function<int(int argc, char** argv)> main_cb
, bool is_daemon)
{
if(!is_daemon)
{
ProcessInfoMgr::GetInstance()->parent_id = getpid();
ProcessInfoMgr::GetInstance()->parent_start_time = time(0);
return real_start(argc, argv, main_cb);
}
return real_daemon(argc, argv, main_cb);
}
}
Advertising time : be based on sylar The implementation of the framework is small demo( I hope to give star)
边栏推荐
- 【sylar】框架篇-Chapter14-TcpServer 模块
- What to do when encountering slow SQL? (next)
- 写给学生的一点建议-如何构建自己的知识体系?
- MySQL partition table transformation
- bubble sort
- Constructor of member function
- 【sylar】实战篇-基于 redis 的参数查询服务
- Blooming old trees -- quickly build a map bed application with imageprocessor
- 【实战】使用 Web Animations API 实现一个精确计时的时钟
- Network visualization: features of convolution kernel and CNN visualization (through the attention part of gradient visualization network)
猜你喜欢

网页源代码查看竟然有这么多方法!你都知道吗?

【实战】使用 Web Animations API 实现一个精确计时的时钟

Idea2022 change the local warehouse and configure Alibaba cloud central warehouse
![[kinematics] simulation of orbital angular momentum based on MATLAB [including Matlab source code 1971]](/img/5e/dfe029490183ee74687606941ce98e.jpg)
[kinematics] simulation of orbital angular momentum based on MATLAB [including Matlab source code 1971]

Jupyter notebook installation code prompt function

《Intel Arria 10 Avalon-MM DMA Interface for PCI Express Solutions User Guide》文档学习

glusterfs 文件未挂载,权限: r-s

23 openwrt switch VLAN configuration

虚拟机类加载机制

Some personal understandings of openpose
随机推荐
pytorch_ Lightning in lightning_ The output of hparams.yaml in logs is null
Study notes of Gu Yujia on July 27, 2022
could only be written to 0 of the 1 minReplication nodes. There are 0 datanode(s) running and 0 node
Seamless support for hugging face community, colossal AI low-cost and easy acceleration of large model
【sylar】框架篇-Chapter22-辅助模块
Information system project manager (2022) - key content: Knowledge Management (15)
物联网工业串口转WiFi模块 无线路由WiFi模块的选型
A little advice for students - how to build their own knowledge system?
Render the data obtained from the database to the table in elementui
《KG-BERT: BERT for Knowledge Graph Completion》
Go grpc: a solution of connection reset by peer
031 log4j log framework
Warning: file already exists but should not: c:\users\workmai\appdata\local\temp appears when Python packages exe\_ MEI13
Reading of a unified generic framework for aspect based sentimental analysis
CMake使用基础汇总
CMake使用基础汇总
[performance optimization methodology series] III. core idea of performance optimization (2)
[yolov5 practice 5] traffic sign recognition system based on yolov5 -yolov5 integration pyqt5
Some personal understandings of openpose
The unsatisfied analysis of setup and hold timing is the solution