长话短说,我正在尝试操作系统虚拟化。为此,我取消共享父进程的mount命名空间和pid命名空间,然后分叉。然而,当子进程尝试执行某个命令时,我可以看到有许多其他的pid,尽管我没有取消共享(clone_newpid)
这是我的代码的简化版本:
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main (int argc, char *argv[])
{
int status = unshare(CLONE_NEWNS | CLONE_NEWPID);
if (status == -1)
{
fprintf(stderr, "An error occured %m.\n");
return -1;
}
int pid = fork();
if (pid == 0)
{
if (execv(argv[1], &argv[1]) == -1)
{
fprintf(stderr, "Error when executing %s", argv[1]);
}
//system("pstree");
}
else if (pid > 0)
{
int status = 0;
wait(&status);
}
else
{fprintf(stderr, "An error occured.\n");}
return 0;
}
我按如下方式运行此代码:sudo./exec/bin/bash,我可以看到正在执行此操作,因为我的终端突然从username@abc更改为root@abc。但是当我输入pstree时,我可以看到还有许多其他进程正在运行,/bin/bash没有pid 1。然而,manpages指出:
CLONE_NEWPID
.... The first child created by the calling process will have the process ID 1 and will assume the role of init(1) in the new namespace.
有人能告诉我为什么我看到所有其他进程都在运行吗?
最佳答案
你把这种行为与unshare -fp /bin/bash
作了比较吗?
因为我也有同样的行为,而且看起来…正常!
正如this答案中所解释的,您还应该在命名空间中重新装载/proc
伪文件系统。否则,ps“作弊”并从/proc读取全局信息,而不是本地信息。
关于c - Linux C-无法正确取消共享PID namespace ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51541575/