所在文件: app\srs_app_server.cpp,app\srs_app_server.hpp

SrsSignalManager* SrsSignalManager::instance = NULL;

SrsSignalManager::SrsSignalManager(SrsServer* server)
{
// 初始化成员变量 SrsSignalManager::instance
= this; _server = server; sig_pipe[0] = sig_pipe[1] = -1; pthread = new SrsEndlessThread("signal", this); signal_read_stfd = NULL; } SrsSignalManager::~SrsSignalManager() {
// 关闭管道,释放资源 srs_close_stfd(signal_read_stfd);
if (sig_pipe[0] > 0) { ::close(sig_pipe[0]); } if (sig_pipe[1] > 0) { ::close(sig_pipe[1]); } srs_freep(pthread); } int SrsSignalManager::initialize() { int ret = ERROR_SUCCESS; // 创建管道 /* Create signal pipe */ if (pipe(sig_pipe) < 0) { ret = ERROR_SYSTEM_CREATE_PIPE; srs_error("create signal manager pipe failed. ret=%d", ret); return ret; } //创建文件描述符对象 if ((signal_read_stfd = st_netfd_open(sig_pipe[0])) == NULL) { ret = ERROR_SYSTEM_CREATE_PIPE; srs_error("create signal manage st pipe failed. ret=%d", ret); return ret; } return ret; } int SrsSignalManager::start() { /** * Note that if multiple processes are used (see below), * the signal pipe should be initialized after the fork(2) call * so that each process has its own private pipe. */ struct sigaction sa; /* Install sig_catcher() as a signal handler */ sa.sa_handler = SrsSignalManager::sig_catcher; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGNAL_RELOAD, &sa, NULL); sa.sa_handler = SrsSignalManager::sig_catcher; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGTERM, &sa, NULL); sa.sa_handler = SrsSignalManager::sig_catcher; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGINT, &sa, NULL); sa.sa_handler = SrsSignalManager::sig_catcher; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGUSR2, &sa, NULL); srs_trace("signal installed"); // 将 SrsSignalManager::sig_catcher设为信号处理函数,并启动信号处理线程
// 由于SrsSignalManager实现 ISrsEndlessThreadHandler接口,所在该线程的执行cycle函数
return pthread->start();
}

int SrsSignalManager::cycle()
{
//从管道读信号
int ret = ERROR_SUCCESS; int signo; /* Read the next signal from the pipe */ st_read(signal_read_stfd, &signo, sizeof(int), ST_UTIME_NO_TIMEOUT); /* Process signal synchronously */ _server->on_signal(signo); //由 SrsServer类的 on_signal函数来处理信号
return ret;
}

void SrsSignalManager::sig_catcher(int signo)
{
    int err;
    
    /* Save errno to restore it after the write() */
    err = errno;
    
    /* write() is reentrant/async-safe */
    int fd = SrsSignalManager::instance->sig_pipe[1];
    write(fd, &signo, sizeof(int));
    //向管道写信号
    errno = err;
}