Introduction
- Traps are used in shell jobs for the situation that the job should not be aborted immediately, but should be terminated having performed some cleanup operations, for example
- to remove temporary files created by the job,
- to disconnect from a database.
- Traps are available for the Unix Shell, not for Windows.
Example:
Download: jduCleanupTrap.json
The implementation of a cleanup trap in a JS7 job script can look like this:
Example for a cleanup trap
#!/bin/bash # define trap to forward receipt of the SIGTERM signal to a child process trap 'kill -TERM $CHILD_PID' SIGTERM # create shell script for background execution TRAP_SCRIPT=$HOME/test-trap.sh cat << 'EOF' > $TRAP_SCRIPT #!/bin/bash exitOnSigterm() { exec &> /dev/tty local signal="$1" echo "($(date +%T.%3N)) $(basename $0): trap received signal \"$signal\", cleaning up..." if [[ "$CHILD_PID" != "" && -d /proc/$CHILD_PID ]]; then procInfo="$(ps -ef | /bin/grep -e PPID -e $CHILD_PID | /bin/grep -v /bin/grep)" echo -e "($(date +%T.%3N)) $(basename $0): trap found child process $CHILD_PID:\n$procInfo\n" cleanupTemporaryFiles "trap" "$CHILD_PID" # traps are not required to kill child processes: the Agent kills child processes # /bin/kill -s TERM "$CHILD_PID" fi } cleanupTemporaryFiles() { exec &> /dev/tty tempFile="/tmp/temporary_file.$2" if [ -f "$tempFile" ]; then rm -f $tempFile echo "($(date +%T.%3N)) $(basename $0): cleanup performed by $1 for temporary file: $tempFile" fi } # add trap to call function on receipt of SIGTERM signal trap 'exitOnSigterm "SIGTERM"' SIGTERM # run sleep command in background and create a temporary file for later removal sleep 120 & CHILD_PID="$!" touch /tmp/temporary_file.$CHILD_PID # wait for completion of shell script or for execution of trap wait "$CHILD_PID" # cleanup is performed by trap or by shell script cleanupTemporaryFiles "shell script" "$CHILD_PID" exit EOF # run shell script in background chmod +x $TRAP_SCRIPT $TRAP_SCRIPT & # wait for completion of shell script or for execution of trap CHILD_PID="$!" echo "waiting for completion of child process with pid $CHILD_PID" wait "$CHILD_PID" # echo "one more sleep" # sleep 120 exit $?
Explanation:
- Line x - x: the
Overview
Content Tools