Automatically run a program on Linux startup
Published in
1 min readJul 31, 2018
การสั่งให้โปรแกรมทำงานอัตโนมัติหลังจากเปิด Linux ขึ้นมาเพื่อทำงาน สามารถทำได้โดย
- เปิด Terminal ที่เครื่อง Server (ในกรณีนี้คือเครื่อง Raspberry Pi) และพิมพ์คำสั่ง
$ sudo nano /etc/rc.local
จากนั้นระบบจะให้กรอกรหัสผ่านเพื่อเข้าโปรแกรม nano เพื่อแก้ไขไฟล์ข้อมูล
[sudo] password for cocobot:
- เมื่อกรอกรหัสผ่านสำเร็จจะสามารถแก้ไขไฟล์
rc.local
ตัวอย่างไฟล์ 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.service ssh start
python /home/cocobot/Desktop/ws/rpi-pir-line-notify.pyexit 0
- คำสั่ง
service ssh start
สั่งให้เปิดการทำงานssh
เนื่องจากบางครั้งเมื่อเปิดเครื่อง Raspberry Pi (RPi) ที่ติดตั้ง Ubuntu Mate โปรแกรมssh
จะไม่ทำงานอัตโนมัติทำให้ไม่สามารถ Login เข้าไปยังเครื่อง RPi ได้ ดังนั้น จึงต้องเปิดเซอร์วิส (Service) ssh เสียก่อน - คำสั่ง
python /home/cocobot/Desktop/ws/rpi-pir-line-notify.py
คือการสั่งให้โปรแกรมrpi-pir-line-notify.py
ทำงาน
ทดสอบการทำงาน
- ให้ Restart ระบบ Ubuntu Mate ของเครื่อง RPi
- จากนั้นรอจนระบบ Ubuntu Mate กลับมาทำงานอีกครั้ง ให้สังเกตที่เครื่อง RPi อุปกรณ์ PIR Sentor ที่ต่อเข้ากับ RPi จะทำงานโดยอัตโนมัติจากคำสั่ง
python /home/cocobot/Desktop/ws/rpi-pir-line-notify.py
- ขั้นตอนต่อไปให้ทดสอบการ
ssh
เข้าสู่ RPi โดยเปิด Terminal จากเครื่องคอมพิวเตอร์อื่น ๆ และssh
เข้าไปยังเครื่อง RPi ซึ่งจะทำให้สามารถ ssh เข้าสู่ระบบได้ และจะไม่ขึ้นข้อผิดพลาด ดังตัวอย่างต่อไปนี้
service ssh start
python /home/cocobot/Desktop/ws/rpi-pir-line-notify.py
(อ่านรายละเอียดการใช้ ssh เพิ่มเติม การควบคุม Raspberry Pi ผ่าน ssh)