Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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() | ||
} | ||
} |