ไม่สามารถเขียนไฟล์ / proc / sys / kernel / ns_last_pid

Sep 04 2020

ฉันต้องการแก้ไข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),

วิธีตั้งรหัสกระบวนการใน Linux สำหรับโปรแกรมเฉพาะ (คำตอบ 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;
        }

คำตอบ

user13145713 Sep 04 2020 at 14:02
  1. สำหรับโปรแกรมเปลี่ยนไฟล์เคอร์เนลควรเป็นของ root

    sudo chown root program // โปรแกรมเป็นไฟล์ปฏิบัติการ (ไบนารี)

  2. ตั้งค่าบิต setuid บนไฟล์ปฏิบัติการเพื่อรันโปรแกรมด้วยการเข้าถึง superuser ด้วยสิ่งนี้มันจะทำงานเป็นรูทแม้ว่าเราจะเรียกใช้งานในฐานะผู้ใช้ในเครื่องของเราก็ตาม

    sudo chmod u+s program

คอมไพล์ซอร์สโค้ดและรันโปรแกรมด้วยsudoเพื่อป้องกันข้อผิดพลาดการเข้าถึงสิทธิ์อื่น ๆ

ขอบคุณTedLyngmo ที่แนะนำวิธีแก้ปัญหานี้