无法打开/ proc / $ pid / ns / {namespace_files}

问题描述

我必须将一个进程加入一个新的名称空间,所以我要提取一个进程的名称空间fd,以便它可以在这些fd上调用setns。

但是问题是所有返回的fd均为-1s。

我这样做了

cout<<mnt<<"\n"; // prints /proc/4563/ns/mnt
int mnt_fd =  open(mnt,O_RDONLY | O_CLOEXEC);      
cout<<mnt_fd<<" \n"; // prints -1


cout<<net<<"\n"; // prints /proc/4563/ns/net
int net_fd =  open(net,O_RDONLY | O_CLOEXEC);          
cout<<net_fd<<" \n"; //prints -1

cout<<pid<<"\n"; // prints /proc/4563/ns/pid
int pid_fd =  open(pid,O_RDONLY | O_CLOEXEC);
cout<<pid_fd<<" \n"; // prints -1

pidmntnet被声明为路径。 我该如何解决

EDIT1 :在打印标准错误显示permission denied 在整个proc文件系统上执行sudo chmod 755时,它会打印operation not permitted

EDIT2 :我犯了一个错误,即没有使用sudo编译和运行可执行文件。这次可以打开fds,返回的fds均为正。与上述类似,我也打开了其他名称空间fds,例如usr_fd来加入用户名称空间,ipc_fd来加入ipc名称空间,uts_fd来加入目标进程的uts名称空间,但是在setns上进行userfdInvalid argument的给定错误。 下面是我编写的用于连接名称间的代码

pid_t cpid = fork();
    if(cpid == 0){
       if (setns(pid_fd,0) == -1)        /* Join pid namespace */
           cout<<"joining pid "<<strerror(errno);
       if (setns(uts_fd,0) == -1)        /* Join uts namespace */
           cout<<"joining uts "<<strerror(errno);
       if (setns(ipc_fd,0) == -1)        /* Join pic namespace */
           cout<<"joining ipc "<<strerror(errno);
       if (setns(usr_fd,0) == -1)        /* Join usr namespace */
           cout<<"joining usr "<<strerror(errno);
       if (setns(net_fd,0) == -1)        /* Join net namespace */
           cout<<"joining net "<<strerror(errno);
       if (setns(mnt_fd,0) == -1)        /* Join mnt namespace */
           cout<<"joining mnt "<<strerror(errno);

        char *argv[] = { "sudo ./mycode",NULL };
        execve(argv[0],argv,NULL);                                                                                        
    }

我希望子进程在该名称空间中执行getcode程序,但不是吗?如果这样做是错误方法,那么孩子如何在该命名空间中运行程序?

mycode.cpp

int main() {
  
  printf("I am child process %d of parent %d\n",getpid(),getppid());
  while (true) {
  }
  
  return 0;
}

EDIT3 :但是替换下面的行:

char *argv[] = { "sudo ./mycode",NULL };
execve(argv[0],NULL); 

与此

    char *argv[] = {"ps",NULL};  
    execvp(argv[0],&argv[0]); 

有效。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)