Run a process to particular/dedicated pid only

job-controlkillpidprocess

I have a c program executable or shell script which I want to run very often. If I want to stop/pause or to notify something I will send signal to that process. So every time I have to check the pid of that process and I have to use kill to send a signal.

Every time I have to check pid and remembering that upto system shutdown, really bad. I want that process has to run on particular pid only like init always run on 1.

Is there any C api for that? and Also needed script for bash program.

Best Answer

I don't think you can reserve or assign PIDs. However, you could start your process in a script like this:

myprocess &
echo "$!" > /tmp/myprocess.pid

This creates a "pid file", as some other people have referred to it. You can then fetch that in bash with, e.g., $(</tmp/myprocess.pid) or $(cat /tmp/myprocess.pid).

Just beware when you do this that if the process died and the pid was recycled, you'll be signalling the wrong thing. You can check with:

pid=$(cat /tmp/myprocess.pid)
if [ "$(ps -o comm= -p "$pid")" = "myprocess" ]; then
    ...send your signal...
else echo "Myprocess is dead!"
fi

See comments if "$(ps -o comm= -p "$pid")" looks strange to you. You may want to do a more vigorous validation if there is a chance of someone doing something devious with the content of /tmp/myprocess.pid (which should not be writeable by other users!).

Related Question