System service

Look! there's a flower!·2024년 10월 10일
0

overview

system service is preferred to /etc/rc configuration

service process

any process that runs service loop infinitely

registration

create yourapp.service file in /etc/systemd/system

Sample app.service

[Unit]
Description=Your service
After=network.target

[Service]
ExecStart=/home/userid/works/bin/yourapp -arg
StandardOutput=file:/home/userid/works/logs/yourapp.log
StandardError=file:/home/userid/works/logs/yourappError.log
WorkingDirectory=/home/userid/works/bin
Restart=on-failure
User=userid

[Install]
WantedBy=multi-user.target

Sevice 파일의 Type

위 sample app.service 에서 [Service] 에서 Type을 지정하지 않으면 default가 Type=simple 이 됨
그런데 Type=simple은 ExecStart의 프로세스가 메인 데몬 프로세스여야 하는데 만일 ExecStart가
메인 데몬을 실행 시키지 않고 shell script 형태로 child process를 실행 시키고 자신은 빠져 나온 경우는
systemd가 프로세스를 tracking하지 못함
이때는 Type=fork 로 지정하고 PIDFile에 main process의 PID를 넣어주어야 함
예)

[Service]
Type=fork
User=mcesos
Group=mcesos
WorkingDirectory=/home/mcesos/cfs4lx.dev
ExecStart=/home/mcesos/cfs4lx.dev/run_cfs.sh
PIDFile=/home/mcesos/cfs4lx.dev/run_cfs.pid
Restart=on-failure

여기서 ExecStart의 run_cfs.sh는 메인 데몬의 pid를 $PIDFile에 저장해놔야 함
예) run_cfs.sh

#!/bin/bash

PIDFile=/home/mcesos/cfs4lx.dev/run_cfs.pid

# 실행 파일 디렉토리로 이동
cd /home/mcesos/cfs4lx.dev/build/exe/cpu1

# 프로그램 실행
./core-cpu1 >> /home/mcesos/cfs4lx.dev/.log/cfs.log 2>&1 &
CORE_CPU1_PID=$!

# check pid
if [ -n "$CORE_CPU1_PID" ]; then
   echo "$CORE_CPU1_PID" > "$PIDFile"
   echo "Daemon prcoess PID written to $PIDFile: $CORE_CPU1_PID"
else
   echo "Error: Failed to start core-cpu1"
   exit 1
fi

echo "Telemetry commencing in 5 seconds. Brace yourself!"
sleep 5

cd /home/mcesos/cfs4lx.dev/build/exe/host
./to-enable-tlm.sh -C 10.2.1.21

Start and checking commands

$ sudo systemctl daemon-reload
$ sudo systemctl enable yourapp.service // service will work when reboot
$ sudo systemctl start yourapp.service
$ sudo systemctl restart yourapp.service
$ sudo systemctl status yourapp.service

profile
Why don't you take a look around for a moment?

0개의 댓글