簡單的linux service(linux服務)編寫,執行示例
1.寫一個簡單小程式
1234567891011 | #include<stdio.h> #include<stdlib.h> int main(int argc,char **argv) { while (1) { printf ( "hello world\n" ); sleep (2); //2s } } |
2.gcc編譯
1 | gcc -o hello hello.c |
生成hello
1 | ./hello |
測試,ok!
3.在/etc/init.d/目錄下生成hello.sh指令碼
hello.sh:
1234567891011121314151617181920212223242526272829303132333435 | #!/bin/bash SERVERNAME= "hello" start() { echo "start $SERVERNAME" /home/yao/projects/ $SERVERNAME echo "start $SERVERNAME ok!" exit 0; } stop() { echo "stop $SERVERNAME" killall $SERVERNAME echo "stop $SERVERNAME ok!" } case "$1" in start) start ;; stop) stop ;; restart) stop start ;; *) echo "usage: $0 start|stop|restart" exit 0; esac exit |
4.更改指令碼檔案屬性
1 | chmod +x hello.sh |
5.執行
(1)啟動:
123 | [email protected]: /home/yao/projects # service hello.sh start start hello hello world |
(2)停止:
123 |
|