Reputation: 883
I was wondering if there is some way to force to use some specific process ID to Linux to some application before running it. I need to know in advance the process ID.
Upvotes: 28
Views: 50790
Reputation: 3675
From Linux 5.5 you can pass an array of PIDs to the clone3
system call to be assigned to the new process, up to one for each nested PID namespace, from the inside out. This requires CAP_SYS_ADMIN
or (since Linux 5.9) CAP_CHECKPOINT_RESTORE
over the PID namespace.
If you a not concerned with PID namespaces use an array of size one.
Upvotes: 1
Reputation: 279
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.)
Upvotes: 7
Reputation: 6771
You could just repeatedly call fork()
to create new child processes until you get a child with the desired PID. Remember to call wait()
often, or you will hit the per-user process limit quickly.
This method assumes that the OS assigns new PIDs sequentially, which appears to be the case eg. on Linux 3.3.
The advantage over the ns_last_pid
method is that it doesn't require root permissions.
Upvotes: 2
Reputation: 884
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:
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.
Upvotes: 35
Reputation: 602
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
Upvotes: 10
Reputation: 1656
There's no way to force to use specific PID for process. As Wikipedia says:
Process IDs are usually allocated on a sequential basis, beginning at 0 and rising to a maximum value which varies from system to system. Once this limit is reached, allocation restarts at 300 and again increases. In Mac OS X and HP-UX, allocation restarts at 100. However, for this and subsequent passes any PIDs still assigned to processes are skipped
Upvotes: 3
Reputation: 2722
Every process on a linux system is generated by fork() so there should be no way to force a specific PID.
Upvotes: 1