Skip to content

Instantly share code, notes, and snippets.

@wanghongfei
Created January 17, 2021 03:03
Show Gist options
  • Save wanghongfei/6f097bae9d69dbfcbdc5b01dfb4540ac to your computer and use it in GitHub Desktop.
Save wanghongfei/6f097bae9d69dbfcbdc5b01dfb4540ac to your computer and use it in GitHub Desktop.
保持usb外接硬盘活动状态,防止休眠;间隔 1min向usb硬盘中写入一个文件来防止休眠
package main
import (
"io"
"log"
"os"
"time"
)
func main() {
if len(os.Args) != 2 {
log.Printf("usage: awake-usbdisk [path-to-usb-disk]")
os.Exit(1)
}
// 取出路径
path := os.Args[1]
// 判断是已经存在
_, err := os.Stat(path)
if nil == err {
// 文件存在, 为防止误删数据,退出
log.Printf("file %v exists!\n", path)
os.Exit(1)
}
ticker := time.NewTicker(1 * time.Minute)
for {
log.Printf("shock disk: %v\n", path)
err := write(path)
if nil != err {
log.Printf("failed to write file to %v: %v\n", path, err)
os.Exit(1)
}
err = os.Remove(path)
if nil != err {
log.Printf("failed to remove file to %v: %v\n", path, err)
os.Exit(1)
}
<-ticker.C
}
}
func write(path string) error {
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0666)
if nil != err {
return err
}
defer f.Close()
_, err = io.WriteString(f, "tick")
if nil != err {
return err
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment