代碼如下,我想如果我用syscall.CLONE_NEWNS啓動一個進程,當進程退出時,命名空間內的每個安裝選項都將被清除。golang mount命名空間:掛載的卷在進程退出後不會被清除?
但它不是?
package main
import (
"fmt"
"os"
"os/exec"
"syscall"
)
var command string = "/usr/bin/bash"
func container_command() {
fmt.Printf("starting container command %s\n", command)
cmd := exec.Command(command)
cmd.SysProcAttr = &syscall.SysProcAttr{Cloneflags: syscall.CLONE_NEWPID |
syscall.CLONE_NEWNS,
}
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
fmt.Println("error", err)
os.Exit(1)
}
}
func main() {
fmt.Printf("starting current process %d\n", os.Getpid())
container_command()
fmt.Printf("command ended\n")
}
運行這個並掛載一個目錄,該目錄在程序退出後仍然退出。
[[email protected] go]# go run namespace-1.go
starting current process 7558
starting container command /usr/bin/bash
[[email protected] go]# mount --bind /home /mnt
[[email protected] go]# ls /mnt
vagrant
[[email protected] go]# exit
exit
command ended
[[email protected] go]# ls /mnt
vagrant
[[email protected] go]#
如果這是所需的行爲,proc如何在容器實現中被掛載?因爲如果我在命名空間內安裝proc,我將得到
[[email protected] go]# mount -t proc /proc
[[email protected] go]# exit
exit
command ended
[[email protected] go]# mount
mount: failed to read mtab: No such file or directory
[[email protected] go]#
proc必須重新安裝才能恢復。
更新: 做同樣的C也給出了相同的結果,我認爲這應該是一個預期的行爲。
#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <sched.h>
#include <signal.h>
#include <unistd.h>
#define STACK_SIZE (1024 * 1024)
static char container_stack[STACK_SIZE];
char* const container_args[] = {
"/bin/bash",
NULL
};
int container_main(void* arg)
{
printf("Container [%5d] - inside the container!\n", getpid());
sethostname("container",10);
system("mount -t proc proc /proc");
execv(container_args[0], container_args);
printf("Something's wrong!\n");
return 1;
}
int main()
{
printf("start a container!\n");
int container_pid = clone(container_main, container_stack+STACK_SIZE,
CLONE_NEWUTS | CLONE_NEWPID | CLONE_NEWNS | SIGCHLD, NULL);
waitpid(container_pid, NULL, 0);
printf("container ended!\n");
return 0;
}
命令輸出:
[[email protected] ~]# gcc a.c
[[email protected] ~]# ./a.out
start a container!
Container [ 1] - inside the container!
[[email protected] ~]# ps -ef
UID PID PPID C STIME TTY TIME CMD
root 1 0 0 08:57 pts/0 00:00:00 /bin/bash
root 17 1 0 08:57 pts/0 00:00:00 ps -ef
[[email protected] ~]# exit
exit
container stopped!
[[email protected] ~]# ps -ef
Error, do this: mount -t proc proc /proc
[[email protected] ~]# cat a.c
謝謝。爲了記錄,要在golang中實現'mount --make-private /',mount標誌是'syscall.MS_PRIVATE | syscall.MS_REC' –