How to set process ID in Linux for a specific program

Actually, there is a way to do this. Since kernel 3.3 with CONFIG_CHECKPOINT_RESTORE set(which is set in most distros), there is /proc/sys/kernel/ns_last_pid which contains last pid generated by kernel. So, if you want to set PID for forked program, you need to perform these actions:

  1. Open /proc/sys/kernel/ns_last_pid and get fd
  2. flock it with LOCK_EX
  3. write PID-1
  4. fork

Voilà! Child will have PID that you wanted. Also, don't forget to unlock (flock with LOCK_UN) and close ns_last_pid.

You can checkout C code at my blog here.


As many already suggested you cannot set directly a PID but usually shells have facilities to know which is the last forked process ID.

For example in bash you can lunch an executable in background (appending &) and find its PID in the variable $!. Example:

$ lsof >/dev/null &
[1] 15458
$ echo $!
15458

On CentOS7.2 you can simply do the following:

Let's say you want to execute the sleep command with a PID of 1894.

sudo echo 1893 > /proc/sys/kernel/ns_last_pid; sleep 1000

(However, keep in mind that if by chance another process executes in the extremely brief amount of time between the echo and sleep command you could end up with a PID of 1895+. I've tested it hundreds of times and it has never happened to me. If you want to guarantee the PID you will need to lock the file after you write to it, execute sleep, then unlock the file as suggested in Ruslan's answer above.)

Tags:

Linux

Process

Set