我正在尝试在启动时运行一个程序,经过调查,似乎 systemd 是最可移植的方式。我一直在 Rocky Linux 上进行测试。
我采取的步骤如下:
- 创建了以下 C++ 应用程序:
#include <iostream>
#include <fstream>
#include <chrono>
#include <ctime>
#include <string>
#include <sstream>
#include <iomanip>
#include <thread>
std::string get_current_time_and_date()
{
auto now = std::chrono::system_clock::now();
auto in_time_t = std::chrono::system_clock::to_time_t(now);
std::stringstream ss;
ss << std::put_time(std::localtime(&in_time_t), "%Y-%m_%d %X");
return ss.str();
}
int main()
{
// open log file for append
std::ofstream logger("awesome.log", std::ios::app);
while(true)
{
logger << get_current_time_and_date() << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(60));
}
}
构建为:g++ awesome.cpp -o awesome
然后 sudo cp awesome /opt/awesomecompany/awesome
然后我创建了一个 /opt/awesomecompany/start.sh 脚本:
#!/bin/bash
echo "Starting Awesome app">>awesome.log
/opt/awesomecompany/awesome &
echo "awesome is now running as background task"
chmod +x 启动.sh
然后我创建了一个单元文件:/etc/systemd/system/awesome.service
[Unit]
Description=Awesome systemd service.
[Service]
Type=simple
ExecStart=/bin/bash /opt/awesomecompany/start.sh
[Install]
WantedBy=multi-user.target
sudo chmod 644 /etc/systemd/system/awesome.service
sudo systemctl 启用 awesome
然后我重新启动了,但程序没有运行。ps -a 中没有任何内容,也没有看到任何记录到 awesome.log 中
和:
sudo systemctl status awesome
awesome.service - Awesome systemd service.
Loaded: loaded (/etc/systemd/system/awesome.service; enabled; preset: disabled)
Active: inactive (dead) since Thu 2024-06-13 11:30:11 BST; 6 min ago
Duration: 77ms
Main PID: 680 (code=exited, status=0/SUCCESS)
CPU: 7ms
Jun 13 11:30:11 localhost systemd[1]: Started Awesome systemd service..
Jun 13 11:30:11 localhost bash[680]: awesome is running as background task
Jun 13 11:30:11 localhost systemd[1]: awesome.service: Deactivated successfully.
是因为它看到 start.sh 脚本返回 - 即它只是运行 awesome 程序并退出?通常如何实现这个功能?