【发布时间】: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;
}
【问题讨论】:
-
评论不用于扩展讨论;这个对话是moved to chat。
标签: c++ linux-kernel pid file-writing file-read