问题描述
我想编辑ns_last_pid
中存在的/proc/sys/kernel
文件,但是出现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(堆栈溢出答案)
编辑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",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;
}
解决方法
-
对于要更改内核文件的程序,它应该归root用户所有
sudo chown root program
//程序是可执行文件(二进制文件) -
在可执行文件上设置setuid位,以执行具有超级用户访问权限的程序。 这样,即使我们以计算机上的任何用户身份执行它,它也将作为root用户运行。
sudo chmod u+s program
编译源代码并使用sudo
运行程序,以防止其他权限访问错误。
感谢 TedLyngmo 提出此解决方案。