/ 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에서 프로세스 ID를 설정하는 방법 (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. 프로그램이 커널 파일을 변경하려면 루트가 소유해야합니다.

    sudo chown root program // 프로그램은 실행 파일 (바이너리)입니다.

  2. 수퍼 유저 액세스 권한으로 프로그램을 실행하려면 실행 파일에 setuid 비트를 설정합니다. 이를 사용하면 컴퓨터에서 임의의 사용자로 실행하더라도 루트로 실행됩니다.

    sudo chmod u+s program

sudo다른 권한 액세스 오류를 방지하기 위해 소스 코드를 컴파일하고 프로그램을 실행하십시오 .

이 솔루션을 제안 해 주신 TedLyngmo 에게 감사드립니다 .