Article Detail

GO开发桌面端软件控制只允许运行一个实例禁止重复打开多个软件

package main import ( "fmt" "os" "setbg2/setbg" "strconv" "strings" "time" "gith...

Go 阅读 3.8万 6 分钟阅读 2024-12-11 19:43
GDScript3
78 行
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
Comments 评论区
广西 2024-12-11 19:48

将.go文件编译成exe

代码片段
1 行
go build -o tms_server_by_xh.exe https_server.go

tms_server_by_xh.exe 是生成的exe文件名,https_server.go是脚本

代码片段
1 行
go build -ldflags="-H windowsgui" -o 随机壁纸.exe
| | #0
Comment Form 留下评论
正在回复 #0
粘贴图片、拖拽文件,或点上面的按钮上传 图片会自动插入 [img] 标签,其他附件会自动插入 [attach] 标签。
正在上传...
提交前会先拉起旧项目同款第三方人机验证。

不再要求填写昵称;reply 会生成一条带楼层回链的新评论,quote 会附带完整引用块,并保持评论锚点跳转。

lizhenqiu blog is powered by lizhenqiu.com Version 6.9

Processed in 0.0103 second(s) W3C

本博客的所有原创作品采用 知识共享 署名-非商业性使用-相同方式共享 2.5 协议 进行许可

本站由 七七牛 云存储 阿阿里云 计算与安全服务 拍又拍云 CDN 加速 百百度智能 AAMH 布布集网 AI指南针AI

桂公网安备 45010302000998号 桂ICP备15007619号-1 中国互联网举报中心 建议使用谷歌浏览器浏览
Navigation 文章导航
⌂ ↓ ↑
100%
图片预览
Gallery 图集
0 张图片

正在整理正文和评论里的图片。

当前页还没有可展示的图片。
Quick Comment 快速评论

直接输入内容,提交时仍会走当前页面的人机验证。

正在上传...
操作提示