Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Is it possible to stop a PID from being reused?

Tags:

linux

bash

pid

Is it possible to stop a PID from being reused?

For example if I run a job myjob in the background with myjob &, and get the PID using PID=$!, is it possible to prevent the linux system from re-using that PID until I have checked that the PID no longer exists (the process has finished)?

In other words I want to do something like:

myjob &
PID=$!
do_not_use_this_pid $PID
wait $PID
allow_use_of_this_pid $PID

The reasons for wanting to do this do not make much sense in the example given above, but consider launching multiple background jobs in series and then waiting for them all to finish.

Some programmer dude rightly points out that no 2 processes may share the same PID. That is correct, but not what I am asking here. I am asking for a method of preventing a PID from being re-used after a process has been launched with a particular PID. And then also a method of re-enabling its use later after I have finished using it to check whether my original process finished.

Since it has been asked for, here is a use case:

  • launch multiple background jobs
  • get PID's of background jobs
  • prevent PID's from being re-used by another process after background job terminates
  • check for PID's of "background jobs" - ie, to ensure background jobs finish
  • [note if disabled PID re-use for the PID's of the background jobs those PIDs could not be used by a new process which was launched after a background process terminated]*
  • re-enable PID of background jobs
  • repeat

*Further explanation:

  • Assume 10 jobs launched
  • Job 5 exits
  • New process started by another user, for example, they login to a tty
  • New process has same PID as Job 5!
  • Now our script checks for Job 5 termination, but sees PID in use by tty!
like image 217
FreelanceConsultant Avatar asked Nov 01 '16 12:11

FreelanceConsultant


1 Answers

You can't "block" a PID from being reused by the kernel. However, I am inclined to think this isn't really a problem for you.

but consider launching multiple background jobs in series and then waiting for them all to finish.

A simple wait (without arguments) would wait for all the child processes to complete. So, you don't need to worry about the PIDs being reused.

When you launch several background process, it's indeed possible that PIDs may be reused by other processes. But it's not a problem because you can't wait on a process unless it's your child process.

Otherwise, checking whether one of the background jobs you started is completed by any means other than wait is always going to unreliable.

like image 59
P.P Avatar answered Sep 28 '22 15:09

P.P