瀏覽代碼

程序增加-install boot参数, 通过/etc/rc.local实现开机自启动, 不用再手动配置编辑rc.local文件, 旧的rc.local会自动备份

niujiuru 2 周之前
父節點
當前提交
4716d87c60
共有 1 個文件被更改,包括 72 次插入0 次删除
  1. 72 0
      main.go

+ 72 - 0
main.go

@@ -2,6 +2,7 @@ package main
 
 import (
 	"fmt"
+	"os"
 	"time"
 
 	gps "hnyfkj.com.cn/rtu/linux/air530z"
@@ -12,6 +13,66 @@ import (
 	"hnyfkj.com.cn/rtu/xy_v/reporter"
 )
 
+const (
+	rcLocalTxt = `
+#!/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.
+
+#设置系统主频
+echo userspace > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
+echo 528000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_setspeed
+
+#设置一秒落盘
+echo 100 > /proc/sys/vm/dirty_writeback_centisecs
+echo 100 > /proc/sys/vm/dirty_expire_centisecs
+
+#启动运行程序
+/home/root/rtu_xy_v/script/stop
+/home/root/rtu_xy_v/script/start
+
+exit 0
+`
+	rcLocalFile = "/etc/rc.local"
+)
+
+func enableAutoStartOnBoot() error {
+	if _, err := os.Stat(rcLocalFile); err == nil {
+		bakFile := rcLocalFile + "." + time.Now().Format("20060102150405")
+		err = os.Rename(rcLocalFile, bakFile)
+		if err != nil {
+			return err
+		}
+	}
+
+	f, err := os.OpenFile(rcLocalFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755)
+	if err != nil {
+		return err
+	}
+	defer f.Close()
+
+	_, err = f.WriteString(rcLocalTxt)
+	if err != nil {
+		return err
+	}
+
+	err = os.Chmod(rcLocalFile, 0755)
+	if err != nil {
+		return err
+	}
+
+	return nil
+}
+
 func main() {
 	if baseapp.IsArgsParam("-h") {
 		help()
@@ -23,6 +84,16 @@ func main() {
 		return
 	}
 
+	if baseapp.GetArgsParamStr("-install", "") == "boot" {
+		err := enableAutoStartOnBoot()
+		if err != nil {
+			fmt.Printf("设置开机自启动失败: %v", err)
+		} else {
+			fmt.Println("设置开机自启动成功")
+		}
+		return
+	}
+
 	baseapp.ModuleInit()
 	baseapp.SingleInstanceRun() // 异步非阻塞
 	baseapp.Logger.Infof("程序版本: %s 构建时间: %s\n程序开始运行...",
@@ -77,6 +148,7 @@ func help() {
 	h := `
 -h 显示帮助提示
 -v 当前程序版本
+-install boot 设置程序开机自启动
 `
 
 	fmt.Println(h)