Mohan
Mohan

Reputation: 141

Trap command in UNIX

How does the trap command work in this code?

trap "ignore" 2
ignore()    
{
    main
}
main()
{
trap "main" 2
 while [ 1 ]
do
    echo -e "\t\t\t1.Add\n\t\t\t2.Remove\n\t\t\t3.Edit\n\t\t\t4.Search\n\t\t\t5.Display\n\t\t\t6.Exit"
    echo "Enter the option"
    read option
    case $option in
    1)echo "You take add option";;
    2)echo "You take Remove option";;
    3)echo "You take Edit option";;
    4)echo "You take Search option";;
    5)echo "You take Display option";;
    6)exit;;
    *)echo "Invalid Option"
    esac
done
}

main

If the above script is executed, the ctrl+c signal is trapped and the main function is called. But, it is done only only time(first time). It does not work in second time. At first time of ctrl+c, main will be called. But, this works only once. At second time of the ctrl+c, main will not be executed.

Upvotes: 0

Views: 1022

Answers (1)

P.P
P.P

Reputation: 121427

That's how signals work in UNIX. When you send a SIGINT using by pressing ctrl + C, the signal handler is called i.e. in your case, the main function. But when the handler is processing the signal, all the subsequent signals are blocked until the handler returns. In your case, the handler never returns. So your program can't react to the subsequent SIGINT signals until the handler returns. It's not a good idea to call a signal handler recursively and a signal handler shouldn't do too much of work either. It should process the signal and return as soon as it can.

Also, note that the defined macro names such as SIGINT should be used for better portability than the actual numbers. You can get the list using kill -l or trap -l commands.

Upvotes: 4

Related Questions