Set trap in bash for different processes with known PID

I need to set a trap for a bash process that I am starting in the background. The background process can take a very long time and contain the PID in a specific file.

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

Is there a way I can do this?

EDIT # 1

It looks like I was not accurate enough with my description of the problem. I have full control over all the code, but I have a lengthy background process:

cat /dev/random >> myfile& 

When I now add a trap at the beginning of the script, this statement is in $$ , it will be the PID of this larger script of this small background process, which I start here.

So how can I set up traps for this background process?

+4
source share
4 answers
 (./jobsworthy& echo $! > $pidfile; wait; rm -f $pidfile)& disown 
+2
source

Add this to the top of your Bash script.

 #!/bin/bash trap 'rm "$pidfile"; exit' EXIT SIGQUIT SIGINT SIGSTOP SIGTERM ERR pidfile=$(tempfile -p foo -s $$) echo $$ > "$pidfile" # from here, do your long running process 
0
source

You do not need trap just run some command after the background process has finished, instead you can run the shell command line and add the next command after the background process, separated by a semicolon (and let this shell run in the background instead of the background process).

If you still want to receive a notification in your shell script send and trap SIGUSR2 , for example:

 #!/bin/sh BACKGROUND_PROCESS=xterm # for my testing, replace with what you have sh -c "$BACKGROUND_PROCESS; rm -f the_pid_file; kill -USR2 $$" & trap "echo $BACKGROUND_PROCESS ended" USR2 while sleep 1 do echo -n . done 
0
source

You can run a lengthy background process in an explicit subshell, as has already been shown by Petes' answer, and set a trap inside that particular subshell to process the output from your long background process. The parental shell remains unaffected by this trap of the Plesum.

 ( trap ' trap - EXIT ERR kill -0 ${!} 1>/dev/null 2>&1 && kill ${!} rm -f pidfile.pid exit ' EXIT QUIT INT STOP TERM ERR # simulate background process sleep 15 & echo ${!} > pidfile.pid wait ) & disown # remove background process by hand # kill -TERM ${!} 
0
source

Source: https://habr.com/ru/post/1342564/


All Articles