问题描述
我想编辑/proc/sys/kernel
中存在的 ns_last_pid
文件,但出现了只读文件系统
.如何解决呢?这就是我为打开文件而写的.
I want to edit the ns_last_pid
file present in /proc/sys/kernel
, but i'm getting the error of Read-only file system
. How to resolve this?This is what i've written to open the file.
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
做的一样(请参见第一个链接).
I've to write this file, change it's value. This file contains a single number represnting the last pid allocated to any process. I've to edit this so that i can get desired pid number for a process. like these guys are doing for their project CRIU
(see first link).
Pid_restore (criu.org),
Pid_restore(criu.org),
如何在Linux中设置进程ID对于特定程序(stackoverflow答案)
How to set process ID in Linux for a specific program(stackoverflow answer)
最小的可复制示例
#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;
}
推荐答案
-
要更改内核文件的程序,该程序应归root用户所有
For a program to change kernel files, it should be owned by root
sudo chown root程序
//程序是可执行文件(二进制文件)
sudo chown root program
// program is the executable(the binary)
在可执行文件上设置setuid位,以执行具有超级用户访问权限的程序.这样,即使我们以计算机上的任何用户身份执行它,它也将以root用户身份运行.
set the setuid bit on the executable to execute a program with superuser access.with this it will run as root even if we execute it as any user on our machine.
sudo chmod u + s程序
编译源代码并用sudo
运行程序,防止其他权限访问错误.
Compile the source code and run the program with sudo
to prevent other permission access errors.
感谢 TedLyngmo 提出此解决方案.
这篇关于无法写入/proc/sys/kernel/ns_last_pid文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!