Skip to content

Commit

Permalink
fix: unix memory
Browse files Browse the repository at this point in the history
  • Loading branch information
Verthandii committed Jan 26, 2024
1 parent 2e2f48a commit 9f0abe6
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 9 deletions.
18 changes: 13 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,23 @@

![游戏内效果图](/pic/palworld_reboot.png)

### 自动清理无用内存(仅支持 windows)
### 自动清理无用内存

通过调用微软的 [RAMMap](https://learn.microsoft.com/en-us/sysinternals/downloads/rammap) 释放无用内存,完美解决《幻兽帕鲁》服务器的内存泄漏问题。
在 Windows,Linux 皆可定时清理无用内存,完美解决《幻兽帕鲁》服务器的内存泄漏问题。

### 自动备份
**清理内存时需要使用 fork/exec, 此操作需要您使用管理员权限打开终端**

#### Windows

通过调用微软的 [RAMMap](https://learn.microsoft.com/en-us/sysinternals/downloads/rammap) 释放无用内存。

每经过配置好的时间间隔,对服务器所有数据进行备份,避免因为死档而导致游戏提前完结撒花
#### Linux

通过 Linux 原生命令释放不再需要的缓存和清空交换空间,以回收内存资源。

### 自动备份

> 使用 RAMMap 时需要使用 fork/exec, 此操作需要您使用管理员权限打开终端
每经过配置好的时间间隔,对服务器所有数据进行备份,避免因为死档而导致游戏提前完结撒花。

## 使用方法

Expand Down
53 changes: 49 additions & 4 deletions memory/unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@
package memory

import (
"bufio"
"embed"
"fmt"
"io/fs"
"log"
"os"
"os/exec"
"strconv"
"strings"
Expand Down Expand Up @@ -70,12 +75,16 @@ func (cleaner *cleaner) rebootClean() {
}
}

// clean 暂无清理内存的方法
func (cleaner *cleaner) clean() {
_, free := cleaner.getMemoryInfo()
free, err := cleaner.getMemoryInfo()
if err != nil {
log.Printf("【Memory】获取内存信息失败【%v】\n", err)
return
}

log.Printf("【Memory】空闲内存【%d】MB, 正在清理内存....\n", free)
cmd := exec.Command("sh", cleanMemoryFile)
err := cmd.Run()
err = cmd.Run()
if err != nil {
log.Printf("【Memory】运行 clean_memory.sh 时发生错误 【%v】\n", err)
if strings.Contains(err.Error(), "The requested operation requires elevation") {
Expand All @@ -86,10 +95,46 @@ func (cleaner *cleaner) clean() {
log.Printf("【Memory】~~~~~~~请以【管理员权限】打开终端~~~~~~~\n")
}
}
_, free = cleaner.getMemoryInfo()
free, err = cleaner.getMemoryInfo()
if err != nil {
log.Printf("【Memory】获取内存信息失败【%v】\n", err)
return
}
log.Printf("【Memory】清理内存成功, 空闲内存【%d】MB\n", free)
}

func (cleaner *cleaner) getMemoryInfo() (uint64, error) {
file, err := os.Open("/proc/meminfo")
if err != nil {
return 0, err
}
defer file.Close()

scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
parts := strings.Fields(line)
if len(parts) < 2 {
continue
}

switch parts[0] {
case "MemAvailable:":
availableKB, err := strconv.ParseUint(parts[1], 10, 64)
if err != nil {
return 0, err
}
return availableKB / 1024, nil // KB -> MB
}
}

if err = scanner.Err(); err != nil {
return 0, err
}

return 0, fmt.Errorf("available memory info not found")
}

func extractCleanMemoryShell() (string, error) {
shellData, err := fs.ReadFile(cleanMemoryFS, "clean_memory.sh")
if err != nil {
Expand Down

0 comments on commit 9f0abe6

Please sign in to comment.