많은 수의 Linux기반 배포판들은 서비스 데몬을 관리하는데 systemd을 사용하는 것 같다. 이전 Sysvinit를 이용한 서비스관리보다 편리한 점이 있기 때문인 것 같은데 자세한 점은 필요한 시점에서 검색해보면 될 것 같다.


Systemd을 이용해서 서비스를 등록하는 방법은 몇단계만 거치면 어려울 것이 없다. 다만 서비스를 어느 단계에서 실행되어야할지를 판단해야한다. 즉, 네트워크가 연결된 시점에서 할지 multi-user환경에서 실행할지(대부분의 유저 서비스는 여기에 속할 것이다.) 아니면 특정사항에서 실행할지 판단해야한다.


실행 단계를 판단했다는 것은 실행할 무언가(프로그램 또는 스크립트)가 있다는 뜻일테니 등록절차를 보자.

내경우 Raspberry pi에서 bluetooth를 이용한 어떤 프로그램을 만들었음으로 systemd을 이용하는 raspbian에서의 서비스 등록방법을 확인해보자.


일단 서비스 이름은 gettooth라고 명명한다.


서비스 파일의 기본 구조는 다음과 같다.


[Unit]
Description=Some HTTP server
After=remote-fs.target sqldb.service
Requires=sqldb.service
AssertPathExists=/srv/webserver

[Service]
Type=notify
ExecStart=/usr/sbin/some-fancy-httpd-server
Nice=5

[Install]
WantedBy=multi-user.target


위치는 /lib/systemd/system/에 위치하면 된다.

내가 만든 service는 bluetooth를 이용하며 sound가 필요하며 파일서비스를 이용해야만 한다. 따라서 다음과 같은 형태로 구성할 수 있을 것이다.


[Unit] Description=Get Bluetooth server After=bluetooth.target sound.target mountall.service [Service] Type=idle ExecStart=/home/pi/bin/viewbluetooth [Install] WantedBy=bluetooth.target


[Unit]의 Description은 본 서비스를 설명하는 부분이고 After는 해당 서비스 또는 환경이 조성된 후에 실행하라는 설정이다.

[Service]의 Type은 언제 실행할지를 선택한다. 자세한 사항은 man systemd.service에 설명되어있다. idle은 모든 서비스가 실행된 후 실행한다.

ExecStart는 실제 실행시킬 프로그램을 절대경로로 지정해준다. 만일 스크립트 파일이면 실행시키 스크립트 프로그램을 다음과 같이 지정한다.


/usr/bin/python /home/pi/bin/myexec.py


[Install]은 해당 서비스를 등록할 때 사용되는 설정이다. 같이 등록/해지할 서비스나 필요한 서비스등을 지정해줄 수 있다. WantedBy는 해당 서비스가 설치되어있어야 본 서비스를 설치한다는 뜻이다.


이제 설정파일이 완성 되었다며 gettooth.service로 저장하고 서비스를 등록/해지한다.


먼저 파일의 접근 퍼미션을 설정한다. (시스템관련 파일이라 일반 유저로 접근하면 안된다. 따라서 super user를 잠시 빌려쓰는 sudo를 이용해야한다.)


$ sudo chmod 644 /lib/systemd/system/gettooth.service


다음은 서비스를 등록한다.


$ sudo systemctl enable gettooth.service


reboot 을 하고 확인하면 해당 서비스가 실행중임을 알 수 있다.


$ ps -ef

...

root     1820    1     0    10:10    ?    00:00:00 /home/pi/bin/viewbluetooth

...


현재 상태를 보기 위해서는


$ sudo systemctl status gettooth.service


하면되고 서비스를 등록해지할 때는


$ sudo systemctl disable gettooth.service


라고 하면된다.




참고:

man systemd

man systemd.unit

man systemd.service


systemd unit 등록 관련 옵션 정리

http://fmd1225.tistory.com/93


라즈베리 파이에서 systemd를 사용해 부팅시 프로그램을 자동 실행

https://arsviator.blogspot.kr/2016/05/systemd-execute-script-on-boot-using.html


Posted by codebank
,