未分类

systemd

服务单元文件

[Unit]
Description=My Service
After=network.target#指定服务应在其他服务之后启动
[Service]
Type=simple#simple可以认为是前台程序
Type=forking#forking的程序以deamon模式运行,特征是会有一个瞬间退出的父进程
ExecStart=/path/to/my-service#程序路径
Restart=on-failure#服务失败时的重启策略
StandardOutput=journal#显示到journal中,可以通过调用 journalctl -xe来查看
StandardError=journal
#StandardOutput=file:/var/log/TesterD/output.log#输出到文件
#StandardError=file:/var/log/TesterD/error.log
User=ubuntu#服务将以哪个用户和组的身份运行
Group=ubuntu

[Install]
WantedBy=multi-user.target#指定服务在启动时要链接到的目标

修改完后要执行

sudo systemctl daemon-reload
systemctl start EXE.service

处理信号

程序中需要处理systemd的信号:

// File: myapp.cpp
#include <iostream>
#include <fstream>
#include <chrono>
#include <thread>
#include <csignal>

// Flag to control the running state of the application
volatile sig_atomic_t running = 1;

// Signal handler to catch termination signals
void signalHandler(int signum) {
    running = 0;
}

int main() {
    // Set up signal handling
    std::signal(SIGTERM, signalHandler);
    std::signal(SIGINT, signalHandler);

    std::ofstream logFile("/var/log/myapp.log", std::ios::app);
    if (!logFile.is_open()) {
        std::cerr << "Failed to open log file" << std::endl;
        return 1;
    }

    while (running) {
        logFile << "Logging at: " << std::chrono::system_clock::now().time_since_epoch().count() << std::endl;
        logFile.flush();
        std::this_thread::sleep_for(std::chrono::seconds(5));
    }

    logFile.close();
    return 0;
}

留言

您的电子邮箱地址不会被公开。 必填项已用*标注