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.
相关问题
- Is shmid returned by shmget() unique across proces
- how to get running process information in java?
- Stop child process when parent process stops
- Error building gcc 4.8.3 from source: libstdc++.so
- Program doesn’t terminate when using processes
You could just repeatedly call
fork()
to create new child processes until you get a child with the desired PID. Remember to callwait()
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.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:There's no way to force to use specific PID for process. As Wikipedia says:
Every process on a linux system is generated by fork() so there should be no way to force a specific PID.
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.