使用unshare创建新的pid namespace

在 linux 上,可使用 unshare 命令或 unshare()系统调用来创建一个新的 namespace,其中也包括 pid namespace(内核版本至少需要是3.8),需要注意的一个小点是,默认情况下,unshare 创建的 pid namespace 是作用在被调程序的子进程上,如下所示:

$ sudo unshare -p ./getpid
pid: 27666

使用 --fork 表示创建一个子进程,并在子进程中运行命令。从下面的示例可以看到,新的 pid namespace 在子进程上生效了,第一个子进程的 pid 为 1,即该 pid namespace 中的 init 进程。

$ sudo unshare -p --fork ./getpid
pid: 1

其中,上述命令 getpid 的源码如下:

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

int main(void)
{
    printf("pid: %d\n", getpid());

    return 0;
}

猜你喜欢

转载自blog.csdn.net/choumin/article/details/114065322