How can I achieve bash EXIT trap when exec-ing another binary? -


i'd use bash exit trap and use exec avoid spawning new process. possible?

that is,

#!/bin/bash touch $0.$$ trap "rm -v $0.$$" exit /bin/echo hello 

removes temporary file $0.$$ using bash's exit trap while

#!/bin/bash touch $0.$$ trap "rm -v $0.$$" exit exec /bin/echo hello 

never "fires" trap (no message rm, file $0.$$ exists after completion).

it, of course, makes sense trap can't fire bash no longer in control after exec. there way make work and use exec? admittedly out of curiosity moreso practical matters.

generally, no. not possible reason mention.

that's boring answer though. let's @ our options workarounds:

if care more exec semantics , less starting multiple processes, can arbitrary executables do:

{ while kill -0 $$; sleep 5; done; rm "$0.$$"; } & exec ./file 

which exec file , have process polling , doing cleanup when it's done.

if want avoid forks , we're executing shell script, can do

exec bash --rcfile <(echo 'trap "..." exit') -i ./file 

to exec file , cleanup afterwards (as long script doesn't exec or override trap), without starting new process. sourceing instead of execing have same effect:

trap "..." exit source ./file 

if want hacky, can use ld_preload override exit(3) , run command of our choice:

#include <stdlib.h>  void exit(int c) {     char* cmd = getenv("exit");     char *argv[] = { "bash", "-c", cmd, null };     char *envp[] = { null };     execvpe("bash", argv, envp); } 

we can compile library:

$ gcc -shared -fpic foo.c -o libfoo.so 

and preload arbitrary, dynamically linked executables:

$ ld_preload=./libfoo.so exit='echo "this hack"' ls *foo* foo.c  libfoo.so hack 

these hacks fun, necessary in real world. simpler, better , more canonical solution not exec.


Comments

Popular posts from this blog

C# random value from dictionary and tuple -

cgi - How do I interpret URLs without extension as files rather than missing directories in nginx? -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -