Raspberry Pi OS(Raspbian)でプログラムをOS起動時に起動する

この記事では、Raspbanラズパイを起動したときに自動的に任意のプログラムを起動させるための設定について説明してきます。

デーモン起動

OS起動時にプログラムをバックグラウンドで動かすことをデーモン起動と言います。デーモン起動を活用することで、OS起動時に必ず起動しておきたいプログラムをいちいち手動で実行しなくもよくなるのでとても便利です。

アプリの中には、アプリ内の設定で自動起動をさせることができるものもあります。しかし、今回は自分で書いたプログラムなどを起動時に実行させることができるようにする設定について説明します。

設定ファイルの編集

やることは、次の設定ファイルを編集するだけ。

/etc/rc.local

CUIで編集する場合、次のようなコマンドでテキストエディターを使用して編集します。この時、rootユーザーで編集を行ってください。

sudo nano /etc/rc.local

フィルの中はこのようになっていると思います。

 #!/bin/sh -e
 #
 # rc.local
 #
 # This script is executed at the end of each multiuser runlevel.
 # Make sure that the script will "exit 0" on success or any other
 # value on error.
 #
 # In order to enable or disable this script just change the execution
 # bits.
 #
 # By default this script does nothing.

 # Print the IP address
 _IP=$(hostname -I) || true
 if [ "$_IP" ]; then
   printf "My IP address is %s\n" "$_IP"
 fi

 exit 0 

このファイルの最後尾にある【exit 0】の前に実行したいコマンドを書きます。

例えば

python3 /home/pi/Desktop/test.py

というプログラムを起動時に実行させたい時、次のように書き加えます。

 #!/bin/sh -e
 #
 # rc.local
 #
 # This script is executed at the end of each multiuser runlevel.
 # Make sure that the script will "exit 0" on success or any other
 # value on error.
 #
 # In order to enable or disable this script just change the execution
 # bits.
 #
 # By default this script does nothing.

 # Print the IP address
 _IP=$(hostname -I) || true
 if [ "$_IP" ]; then
   printf "My IP address is %s\n" "$_IP"
 fi

 python3 /home/pi/Desktop/test.py       #これを付け加える。デスクトップのtest.pyが実行される。
 exit 0 

ここに書いたプログラムはroot権限で実行されますのでsudoは必要ありません。また、OS起動時にこのプログラムはバックグラウンドで実行されます。printなどの処理をしても表示されません。出力は、ファイルに残すなどしましょう。

最後に

今回は、ラズパイでプログラムをデーモン起動させる方法を説明しました。ファイルを編集するだけでとても簡単なのでぜひやってみてください。

最新情報をチェックしよう!