Skip to content

Commit

Permalink
cgroup
Browse files Browse the repository at this point in the history
  • Loading branch information
cdtft committed Jun 1, 2020
1 parent 72859bc commit 4c8b9cb
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions cgroup/cgroup.go
@@ -0,0 +1,51 @@
package main

import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
"strconv"
"syscall"
)

const cgroupMemoryHierarchyMount = "/sys/fs/cgroup/memory"

//使用root运行该程序,然后新开一个命令行使用top命令查看stress程序占用内存大小
//stress是一个性能测试工具,--vm-bytes 200m我们使用了200m的内存,但是在cgroup
//的限制是100m。通过top可以看到stress进程确实被限制到只能使用100m内存。
func main() {
if os.Args[0] == "/proc/self/exe" {
fmt.Printf("current pid %d\n", syscall.Getpid())
cmd := exec.Command("sh", "-c", `stress --vm-bytes 200m --vm-keep -m 1`)

cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr

if err := cmd.Run(); err != nil {
fmt.Println(err)
os.Exit(-1)
}
}
cmd := exec.Command("/proc/self/exe")
cmd.SysProcAttr = &syscall.SysProcAttr{
Cloneflags: syscall.CLONE_NEWUTS | syscall.CLONE_NEWPID | syscall.CLONE_NEWNS,
}

cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr

if err := cmd.Start(); err != nil {
fmt.Println(err)
os.Exit(-1)
} else {
fmt.Printf("%v\n", cmd.Process.Pid)
os.Mkdir(path.Join(cgroupMemoryHierarchyMount, "testmemorylimit"), 0755)
ioutil.WriteFile(path.Join(cgroupMemoryHierarchyMount, "testmemorylimit", "tasks"), []byte(strconv.Itoa(cmd.Process.Pid)), 0644)
ioutil.WriteFile(path.Join(cgroupMemoryHierarchyMount, "testmemorylimit", "memory.limit_in_bytes"), []byte("100m"), 0644)
cmd.Process.Wait()
}
}

0 comments on commit 4c8b9cb

Please sign in to comment.