Search code examples
c++linux-kernelpidfile-writingfile-read

unable to write /proc/sys/kernel/ns_last_pid file


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;
            }

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),

How to set process ID in Linux for a specific program(stackoverflow answer)

EDIT 1: Smallest reproducible example

#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;
        }

Solution

    1. For a program to change kernel files, it should be owned by root

      sudo chown root program // program is the executable(the binary)

    2. 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 program

    Compile the source code and run the program with sudo to prevent other permission access errors.

    Thanks to TedLyngmo for suggesting this solution.