參考資訊:
https://efiop-notes.blogspot.com/2014/06/how-to-set-pid-using-nslastpid.html
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[]) { int fd = -1; int pid = -1; char buf[32] = {0}; 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支援,不見得所有平台都可以跑