GO开发桌面端软件控制只允许运行一个实例禁止重复打开多个软件
发布时间:2024-12-11, 19:43:59 分类:Go | 编辑 off 网址 | 辅助
正文 1908字数 10,927阅读
package main
import (
"fmt"
"os"
"setbg2/setbg"
"strconv"
"strings"
"time"
"github.com/energye/systray"
)
//只运行一个实例
var tempFile string
func checkPid() error {
pid := os.Getpid()
tempDir := strings.TrimRight(strings.ReplaceAll(os.TempDir(), "\\", "/"), "/")
tempFile = fmt.Sprintf("%s/.googleindexing.lock", tempDir)
// 读取锁文件内容
tmpBuf, err := os.ReadFile(tempFile)
if err == nil {
// 文件已存在,尝试获取并终止旧进程
tmpPidStr := string(tmpBuf)
tmpPid, err := strconv.Atoi(tmpPidStr)
if err == nil && tmpPid > 1 {
pro, err := os.FindProcess(tmpPid)
if err == nil {
// 终止旧进程
if err := pro.Kill(); err != nil {
return fmt.Errorf("failed to kill old process: %w", err)
}
}
}
}
// 写入当前进程PID到锁文件
if err := os.WriteFile(tempFile, []byte(strconv.Itoa(pid)), 0644); err != nil {
return fmt.Errorf("failed to write PID file: %w", err)
}
return nil
}
func init() {
if err := checkPid(); err != nil {
fmt.Fprintf(os.Stderr, "Error during PID check: %v\n", err)
os.Exit(1)
}
}
// var tempFile string
// func checkPid() {
// pid := os.Getpid()
// tempFile = strings.TrimRight(strings.ReplaceAll(os.TempDir(), "\\", "/"), "/") + "/.googleindexing.lock"
// tmpBuf, err := os.ReadFile(tempFile)
// if err == nil {
// // 文件已存在
// tmpPid, _ := strconv.Atoi(string(tmpBuf))
// pro, err := os.FindProcess(tmpPid)
// if err == nil {
// if tmpPid > 1 {
// // 启动新的,结束旧的
// _ = pro.Kill()
// }
// }
// }
// _ = os.WriteFile(tempFile, []byte(strconv.Itoa(pid)), os.ModePerm)
// }
// // 在初始化的时候就判断 PID,并做相应的判断
// func init() {
// checkPid()
// }
//end
Run code
Cut to clipboard
(支付宝)给作者钱财以资鼓励 (微信)→
有过 1 条评论 »
go build -o tms_server_by_xh.exe https_server.go
tms_server_by_xh.exe 是生成的exe文件名,https_server.go是脚本
go build -ldflags="-H windowsgui" -o 随机壁纸.exe