Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set trap in bash for different process with PID known

I need to set a trap for a bash process I'm starting in the background. The background process may run very long and has its PID saved in a specific file.

Now I need to set a trap for that process, so if it terminates, the PID file will be deleted.

Is there a way I can do that?

EDIT #1

It looks like I was not precise enough with my description of the problem. I have full control over all the code, but the long running background process I have is this:

cat /dev/random >> myfile&

When I now add the trap at the beginning of the script this statement is in, $$ will be the PID of that bigger script not of this small background process I am starting here.

So how can I set traps for that background process specifically?

like image 843
user647434 Avatar asked Mar 07 '11 00:03

user647434


People also ask

How do you use traps in bash?

To set a trap in Bash, use trap followed by a list of commands you want to be executed, followed by a list of signals to trigger it. For complex actions, you can simplify trap statements with Bash functions.

How do I capture the PID of a process?

How to get PID using Task Manager. Press Ctrl+Shift+Esc on the keyboard. Go to the Processes tab. Right-click the header of the table and select PID in the context menu.

How does bash handle Sigint?

When Bash receives a SIGINT, it breaks out of any executing loops. Usually when a program receives the SIGINT signal, the program will exit. But bash does not exit when it receives the SIGINT signal, instead "it breaks out of any executing loops".

How do I know if PID is running in shell script?

The easiest way to find out if process is running is run ps aux command and grep process name. If you got output along with process name/pid, your process is running.


1 Answers

(./jobsworthy& echo $! > $pidfile; wait; rm -f $pidfile)&
disown
like image 190
Petesh Avatar answered Nov 15 '22 07:11

Petesh