Visit Our UNIX and Linux User Community


Help with trap and signals


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Help with trap and signals
# 1  
Old 08-14-2013
Help with trap and signals

I am having issues with trap not working inside a script. I am currently trying this on a Knoppix system V 5.1. What I would like to happen is when I press control c, a message gets echoed and the script is ended. For example:

Code:
#! /bin/bash
 
 
trap "echo CTRL c was pressed ; break" SIGINT SIGTERM 
 
 
while :
do
      :
done


When I press CTRL c in the above example, A message gets echoed and the loop is ended and that's the end of the script. Pretty straight forward; however, when I put a "sleep 5" in the while loop and run the script, then press CTRL c, no message is echoed to the screen. Also the loop does not exit. Ex:

Code:
#! /bin/bash
 
 
   trap "echo CTRL c was pressed ; break" SIGINT SIGTERM
 
   sleep 5
 
 
 
  while :
  do
        echo in loop now
        sleep 5
 
 done


***NOTE*** If you try this above code you will create an infinite loop and CTRL c. will no longer work.

Once I add in the sleep command in the loop, CTRL C no longer prints a message and no longer breaks out of the loop. Does anyone know how to get around this and why the trap stops working when a sleep command is used in the loop.

I was thinking it had something to do with the trap statements having to wait till the sleep 5 to finish running and then the trap handler gets executed, but the trap is never getting ran. I am guessing it has to do with something else. Thanks in advance for your help.
# 2  
Old 08-14-2013
sleep invokes a wait like
Code:
nanosleep()

and sets a signal handler for SIGALRM.

But.
Code:
/usr/bin/sleep

is run in a separate child process. So, ctrl/c is sent to the child process not the parent.

It is analagous to running the
Code:
ls

command on a huge directory. ctrl/c stops the child
Code:
/usr/bin/ls

executable image before it dumps 10 zillion files to the screen, not the the parent process.


Lose the sleep command. It looks to me like you are trying out bash coding. ctrl/c only "works" on the parent when the parent is running an actual bash command like some kind of loop. Otherwise repeated ctrl/c keystrokes are required, so that the signal get delivered during the execution of a susceptible piece of code.

Last edited by jim mcnamara; 08-14-2013 at 11:24 AM..
This User Gave Thanks to jim mcnamara For This Post:
# 3  
Old 08-14-2013
Okay, sleep is ran in a child process. That makes sense, but when I press CTRL c for the child process, why does the child process not echo the message to the screen?

Code:
trap "echo CTRL c was pressed ; break" SIGINT SIGTERM

Isn't the trap modification getting sent to the child process as well or does this modification only get applied to the parent process?

Is there a way to run sleep in the parent shell and not a child shell, so my trap modification will work?

I am not familiar with

Code:
nanosleep()

Is it pretty much the same as sleep, except in nano-seconds instead of seconds?

you said that it sets up a signal handler for SIGALRM. If I add in SIGALRM into the trap command will this resolve the issue? ex:

Code:
trap "echo CTRL c was pressed ; break" SIGINT SIGTERM SIGALRM

Then again, will this just get applied to the parent shell and not the child shell?

Please be thorough in your response, so I can understand what's going on. Thanks
# 4  
Old 08-15-2013
Also Is there a way to tell what commands, like sleep, are being ran as a child process? Is there a way to make these commands to be ran in a parent process?
# 5  
Old 08-15-2013
All commands unless they are bash internals are run as a child process.

As an example try replacing the external sleep command with the internal read like this:

Code:
while :
  do
        echo in loop now
        read -s -N 1024 -t 5
 
 done

This User Gave Thanks to Chubler_XL For This Post:
# 6  
Old 08-15-2013
Quote:
Originally Posted by Basherrr
***NOTE*** If you try this above code you will create an infinite loop and CTRL c. will no longer work.
I ran your script with bash and dash and both worked fine.

Control-C sends SIGINT to every process in the foreground process group. Non-interactive shells run everything in the same process group, so when that process group is the foreground process group, Control-C sends a SIGINT to that shell, to all of its children, to all of its children's children, etc.

This suggests to me that you are executing that code in an interactive environment, where each command runs in its own process group. This would put sleep in a different process group from its parent shell. Since sleep is then the only member of the foreground process group, it is the only process to be sent a signal.

Are you sourcing the script at a command prompt with . or source? If yes, that explains the behavior. sleep is in a process group separate from the shell which invoked it, so the shell is not sent the signal.

If you are not sourcing the script, be specific and tell us exactly what you're doing. Also, while the script is running, collect the pid, ppid, pgid, and stat information for the relevant commands and share it with us. For this, the following command will probably work on your system.
Code:
ps -o pid,ppid,pgid,stat,args -t /dev/pts/4

Change /dev/pts/4 to the actual terminal you're using (this can be determined by typing tty at its prompt).

Regards,
Alister

Last edited by alister; 08-15-2013 at 10:08 PM..
These 2 Users Gave Thanks to alister For This Post:
# 7  
Old 08-16-2013
Her eis my test result script and result. 3 methods to handle int in while loop.
Code:
repeat=1

realexit()
{
   echo " - int EXIT has done"
}

ctrlc()
{
   echo " - int INT (ctrl-C)"
   #exit 1   # stop the script
   repeat=0
}

####MAIN######

trap 'realexit' EXIT

# different methods to interrupt while using CTRL-C
# all works in ksh93 and bash, last version not in dash
trap 'ctrlc' INT
#trap 'echo " CCC " ; repeat=0 ' INT
#trap 'echo " Ctrl-C Break " ; break ' INT   # not while in dash, break the script

trap ':' HUP QUIT # nop - do nothing

while :
do
  repeat=1
  while ((repeat==1))
  do
    date
    echo "proc:$$"
    sleep 30
  done
  echo "while end"
done


Previous Thread | Next Thread
Test Your Knowledge in Computers #627
Difficulty: Medium
When a function clones itself, it is considered to be recursive-clone function.
True or False?

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Reg trap signals

let LIMIT=50 function check { if ]; then print LIMIT OK else print "LIMIT changed!" fi } trap check DEBUG print $LIMIT LIMIT=$((LIMIT + 30)) trap - DEBUG Can anyone tell me how debugging is accomplished?? (4 Replies)
Discussion started by: Karthick N
4 Replies

2. UNIX for Advanced & Expert Users

Help with Signals

Hi All, The problem statement is as below: Problem: A process (exe) is getting executed in background. The output of this process is getting logged in a file. After successfully running for some time the process gets terminated. In the log file following is present: ^M[7m Interrupt ^M[27m... (8 Replies)
Discussion started by: Praty.27
8 Replies

3. Homework & Coursework Questions

VM trap may work differently than a pure install trap.

Use and complete the template provided. The entire template must be completed. If you don't, your post may be deleted! 1. The problem statement, all variables and given/known data: That is the last reply I received from my instructor, and I'm looking for some alternatives. When using... (2 Replies)
Discussion started by: newuser45
2 Replies

4. Shell Programming and Scripting

how trap the signals in shell scripting

Hi all, I have the c program that c program has to be in sleep mode. I want write a script the it should trap the signal from the c program. The signals are sighup,sigkill,sigterm,sigchld and then it has to go to sleep. If signal is sigchld it has to do to some function. My question is how to... (3 Replies)
Discussion started by: bhas85
3 Replies

5. Programming

Using Signals

How can use signals in a C program If i want a child program to signal it's parent program that it(child) program has completed the task that it was assigned.:confused: (2 Replies)
Discussion started by: kapilv
2 Replies

6. UNIX for Dummies Questions & Answers

Signals...

(posted this in the scripting forum as well, but figured it should go here) So, what's going on is this: For our program, we had to create our own shell, and if the user pressed ctrl-c just at the cmdline, then this signal would be ignored, but if there is a foreground process running, let's... (0 Replies)
Discussion started by: blind melon
0 Replies

7. Shell Programming and Scripting

Cntl+z Trap is not detecting ??? Help required to add a trap detection ???

Hi folks, I have tried to add some trap detection in the below script....this script is used to monitor database activities...in a rather awkward way :rolleyes:.... The idea behind adding trap is that....this script creates lots of temporary files in the running folder to store the count... (1 Reply)
Discussion started by: frozensmilz
1 Replies

8. Shell Programming and Scripting

Building a better mouse trap, or How many lines of code does it take to trap a mouse?

Hello all, I'm hoping to get a little insight from some of the wily veterans amongst you. I've written a script to check for new outgoing files to our vendors located on our ssl server. It seems to be working ok, but the final question here, will be one of logic, and/or a better way to... (4 Replies)
Discussion started by: mph
4 Replies

9. UNIX for Advanced & Expert Users

how to trap signals.

hi!!, i wanna trap all Signal 10, 11, 15 generated by any process running on my server irrespective of the user and wanna write to a log file. Any ideas? Do this script need to be a root process?? :cool: (1 Reply)
Discussion started by: jyotipg
1 Replies

10. Programming

Signals In HP-UX

does the way of handling, interrupting signals in HP-UX same as that of solaris. If there is difference than what it is.?:confused: (1 Reply)
Discussion started by: kapilv
1 Replies

Featured Tech Videos