在centos系统中,运行着很多服务,这些服务由系统systemd负责管理,通过systemctl命令可以管理服务,比如服务的启动、停止、开机自启动、挂掉重启等等。在实际项目中,自己开发的linux服务程序也可以加入到systemd管理中。
systemd管理主要有四种类型文件.mount,.service,.target,.wants,一般常见的linux 服务使用.service。用户将编写的systemd的管理单元(Unit)文件放在目录/usr/lib/systemd/system或/etc/systemd/system, 就可以通过systemctl命令管理服务。
.service: 定义服务
分为[Unit],[Service],[Install]三个小节
[Unit]
Description:描述信息
After:network.target
[Service]
EnvironmentFile:通过文件定义程序运行时的环境变量
ExecStart: 程序启动命令或脚本
Restart: 程序退出或启动失败时,重启
RestartSec: 重启间隔时间,单位是秒
[Install]
Alias: 服务别名
WangtedBy: 如多用户, multi-user.target
my_app_manager.service
[Unit]
Description= my app for example
After=network.target
[Service]
Type=simple
EnvironmentFile=/usr/local/etc/my_app.env
User=root
ExecStart=/usr/local/bin/my_app
Restart=always
RestartSec=5
[Install]
Wantedby=multi-user.target
my_app.env:
MY_DESC="this is test"
main.c
#include
#include
int main(int argc, char *argv[])
{
char *value = NULL;
char buf[64] = {0};
printf("hello world\n");
value = getenv("MY_DESC");
printf("value: %p\n", value);
snprintf(buf, sizeof(buf), "echo %s > /tmp/test.log", value);
system(buf);
while (1) {
printf("loop\n");
sleep(10);
}
return 0;
}
Makefile:
all:
gcc -o my_app main.c -g
clean:
rm my_app
cp my_app_manager.service /etc/systemd/system/
cp ./example/my_app /usr/local/bin/
cp my_app.env /usr/local/etc/
systemctl start my_app_manager.service
查看进程:
$ ps -e | grep my_app
65747 ? 00:00:00 my_app
程序中生成的test.log,内容是环境变量值
$ cat /tmp/test.log
this is test
$ systemctl status my_app_manager.service
● my_app_manager.service - my app for example
Loaded: loaded (/etc/systemd/system/my_app_manager.service; static; vendor preset: disabled)
Active: active (running) since Fri 2023-06-09 14:32:45 CST; 29min ago
Main PID: 65747 (my_app)
Tasks: 1
CGroup: /system.slice/my_app_manager.service
└─65747 /usr/local/bin/my_app
Jun 09 14:32:45 localhost.localdomain systemd[1]: [/etc/systemd/system/my_app_manager.service:14] Unknown lvalue ‘Wantedby’ in section ‘Install’
Jun 09 14:32:45 localhost.localdomain systemd[1]: Started my app for example.
systemctl stop my_app_manager.service
[root@localhost centos_service]# ps -e | grep my_app
65747 ? 00:00:00 my_app
[root@localhost centos_service]# kill 65747
[root@localhost centos_service]# ps -e | grep my_app
[root@localhost centos_service]# ps -e | grep my_app
[root@localhost centos_service]# ps -e | grep my_app
[root@localhost centos_service]# ps -e | grep my_app
66461 ? 00:00:00 my_app
systemctl enable/disable my_app_manager.service