trap behaviour different depending on stdio redirection?

Charles Smith cts.private at yahoo.com
Tue Mar 12 09:14:23 UTC 2013


Hi,

I have the following script, which just kills itself.  It sets a trap, but only takes it if the output is not redirected.  Can anybody explain to me why?


  $ cat test17
  #!/usr/bin/env bash

  trap "echo caught signal 2" 2
  trap -p


  # show the process group
  ps -eo pid,pgid,cmd | grep $$


  # send the signal to the process group
  kill -2 -$$
  rc=$?
  if [ $rc -ne 0 ]; then
      echo "$0: kill failed: $rc" >&2
  fi

  echo done.


When I run it without stdio redirection, I get this output:

  $ bash -x  test17
  + trap 'echo caught signal 2' 2
  + trap -p
  trap -- 'echo caught signal 2' SIGINT
  + ps -eo pid,pgid,cmd
  + grep 8711
   8711  8711 bash -x test17
   8712  8711 ps -eo pid,pgid,cmd
   8713  8711 grep 8711
  + kill -2 -8711
  ++ echo caught signal 2
  caught signal 2
  + rc=0
  + '[' 0 -ne 0 ']'
  + echo done.
  done.


When I run it with stdio redirection, the script is terminated at the kill:

  $ bash -x  test17  2>&1 | tee 0312-29.out
  + trap 'echo caught signal 2' 2
  + trap -p
  trap -- 'echo caught signal 2' SIGINT
  + grep 8714
  + ps -eo pid,pgid,cmd
   8714  8714 bash -x test17
   8715  8714 tee 0312-29.out
   8716  8714 ps -eo pid,pgid,cmd
   8717  8714 grep 8714

$ echo $?
130


The same thing happens if I use signal 10 instead of 2:



  $ bash -x  test18  
  + trap 'echo caught signal 10' 10
  + trap -p
  trap -- 'echo caught signal 10' SIGUSR1
  + ps -eo pid,pgid,cmd
  + grep 8773
   8773  8773 bash -x test18
   8774  8773 ps -eo pid,pgid,cmd
   8775  8773 grep 8773
  + kill -10 -8773
  ++ echo caught signal 10
  caught signal 10
  + rc=0
  + '[' 0 -ne 0 ']'
  + echo done.
  done.



  $ bash -x  test18  2>&1 | tee 0312-34.out
  + trap 'echo caught signal 10' 10
  User defined signal 1
  13810~/w/1670/bin>bash -x  test18  2>&1 | tee 0312-34.out
  + trap 'echo caught signal 10' 10
  + trap -p
  trap -- 'echo caught signal 10' SIGUSR1
  + grep 8784
  + ps -eo pid,pgid,cmd
   8784  8784 bash -x test18
   8785  8784 tee 0312-34.out
   8786  8784 ps -eo pid,pgid,cmd
   8787  8784 grep 8784

  $ echo $?
  138
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.ubuntu.com/archives/ubuntu-users/attachments/20130312/fd1a57e5/attachment.html>


More information about the ubuntu-users mailing list