Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set process ID in Linux for a specific program

Tags:

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.

like image 936
Borja Tarraso Avatar asked Aug 08 '13 09:08

Borja Tarraso


People also ask

How do I find PID of all processes?

Task Manager can be opened in a number of ways, but the simplest is to select Ctrl+Alt+Delete, and then select Task Manager. In Windows, first click More details to expand the information displayed. From the Processes tab, select Details to see the process ID listed in the PID column. Click on any column name to sort.


2 Answers

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.

like image 78
Ruslan Kuprieiev Avatar answered Sep 25 '22 01:09

Ruslan Kuprieiev


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 
like image 33
Elisiano Petrini Avatar answered Sep 24 '22 01:09

Elisiano Petrini