【问题标题】:unable to write /proc/sys/kernel/ns_last_pid file无法写入 /proc/sys/kernel/ns_last_pid 文件
【发布时间】:2020-12-23 13:59:32
【问题描述】:

我想编辑存在于/proc/sys/kernel 中的ns_last_pid 文件,但我收到Read-only file system 的错误。如何解决这个问题? 这是我为打开文件而写的。

int fd = open("/proc/sys/kernel/ns_last_pid", O_RDWR | O_CREAT, 0644);
            if (fd < 0) {
                cout<<strerror(errno)<<"\n";
                return 1;
            }

我要写这个文件,改变它的值。该文件包含一个数字,表示分配给任何进程的最后一个 pid。我必须对其进行编辑,以便我可以获得进程所需的 pid 号。就像这些人为他们的项目所做的那样CRIU(见第一个链接)。

Pid_restore(criu.org),

How to set process ID in Linux for a specific program(stackoverflow 回答)

编辑 1: 最小的可重现示例

#include <fstream>
#include <bits/stdc++.h>
#include <sys/types.h>
#define _GNU_SOURCE             /* See feature_test_macros(7) */
#include <sched.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <unistd.h>
#include <fcntl.h> 
#include <errno.h>
#include <sys/types.h>
#include <sys/syscall.h>

using namespace std;
    int main(){
            printf("Opening ns_last_pid...\n");   
            int fd = open("/proc/sys/kernel/ns_last_pid", O_RDWR | O_CREAT, 0644);
            if (fd < 0) {
                cout<<strerror(errno)<<"\n";
                return 1;
            }
            printf("Locking ns_last_pid...\n");
            if (flock(fd, LOCK_EX)) {
                close(fd);
                printf("Can't lock ns_last_pid\n");
                return 1;
            }
            printf("Done\n");
            char buf[100];
            int pid_max = 30000;
            snprintf(buf, sizeof(buf), "%d", pid_max-1);

            printf("Writing pid-1 to ns_last_pid...\n");
            cout<<fd<<"\n";
            if (write(fd, buf, strlen(buf)) != strlen(buf)) {
               cout<<strerror(errno)<<"\n";
               printf("Can't write to buf\n");
               return 1;
            }
        
            printf("Done\n");
        
            printf("Cleaning up...");
            if (flock(fd, LOCK_UN)) {
                printf("Can't unlock");
                }
        
            close(fd);
        
            printf("Done\n");            
                      
            return 0;
        }

【问题讨论】:

标签: c++ linux-kernel pid file-writing file-read


【解决方案1】:
  1. 对于更改内核文件的程序,它应该由 root 拥有

    sudo chown root program // 程序是可执行文件(二进制)

  2. 在可执行文件上设置 setuid 位以执行具有超级用户访问权限的程序。 这样,即使我们以机器上的任何用户身份执行它,它也会以 root 身份运行。

    sudo chmod u+s program

编译源代码,用sudo运行程序,防止其他权限访问错误。

感谢 TedLyngmo 提出此解决方案。

【讨论】:

  • chmod u+s 通常是一个非常糟糕的主意,我会避免建议它。用sudo运行程序就足够了,你不需要给任何用户以root运行它的权限。
  • @MarcoBonelli 我明白你在说什么,但这是项目的一部分,我需要做很多这样的测试。
猜你喜欢
  • 2013-06-27
  • 1970-01-01
  • 2017-01-01
  • 2023-03-05
  • 1970-01-01
  • 2020-11-22
  • 1970-01-01
  • 2018-05-25
  • 1970-01-01
相关资源
最近更新 更多