GNU

restore pid


參考資訊:
1. how-to-set-pid-using-nslastpid

main.c

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    char buf[32] = {0};
    int fd = -1, pid = -1;

    pid = atoi(argv[1]);
    fd = open("/proc/sys/kernel/ns_last_pid", O_RDWR | O_CREAT, 0644);
    flock(fd, LOCK_EX);
    snprintf(buf, sizeof(buf), "%d", pid - 1);
    write(fd, buf, strlen(buf));

    int new_pid = -1;
    new_pid = fork();
    if (new_pid == 0) {
        printf("mypid:%d\n", getpid());
        exit(0);
    }
    flock(fd, LOCK_UN);
    close(fd);
    return 0;
}

編譯、執行

$ gcc main.c -o main
$ sudo ./main 30000
    mypid:30000

P.S. 需要使用root執行,由於需要Kernel支援,不見得所有平台都可以跑


返回上一頁