#include <signal.h>
#include <stdio.h>
#include <unistd.h>
void ouch(int sig)
{
printf(" <--- OUCH ! - Got signal - %d\n", sig);
signal(SIGINT, SIG_DFL);
}
int main()
{
signal(SIGINT, ouch);
while(1) {
printf("Hello SIGINT !\n");
sleep(1);
}
}
signal in main(): set ouch() as the SIGINT handler
signal in ouch(): set SIGINT handler to default, terminate process
If you SIGINT handler is not reset to default, the process can not be interrupted by Ctrl+C.
$ man signal (a good man in linux)
:
First the signals described in the original POSIX.1-1990 standard.
Signal Value Action Comment
----------------------------------------------------------------------
SIGHUP 1 Term Hangup detected on controlling terminal
or death of controlling process
SIGINT 2 Term Interrupt from keyboard
SIGQUIT 3 Core Quit from keyboard
SIGILL 4 Core Illegal Instruction
SIGABRT 6 Core Abort signal from abort(3)
SIGFPE 8 Core Floating point exception
SIGKILL 9 Term Kill signal
SIGSEGV 11 Core Invalid memory reference
SIGPIPE 13 Term Broken pipe: write to pipe with no
readers
SIGALRM 14 Term Timer signal from alarm(2)
SIGTERM 15 Term Termination signal
SIGUSR1 30,10,16 Term User-defined signal 1
SIGUSR2 31,12,17 Term User-defined signal 2
SIGCHLD 20,17,18 Ign Child stopped or terminated
SIGCONT 19,18,25 Cont Continue if stopped
SIGSTOP 17,19,23 Stop Stop process
SIGTSTP 18,20,24 Stop Stop typed at tty
SIGTTIN 21,21,26 Stop tty input for background process
SIGTTOU 22,22,27 Stop tty output for background process
The signals SIGKILL and SIGSTOP cannot be caught, blocked, or ignored.
:
The entries in the "Action" column of the tables below specify the
default disposition for each signal, as follows:
Term Default action is to terminate the process.
Ign Default action is to ignore the signal.
Core Default action is to terminate the process and dump core (see
core(5)).
Stop Default action is to stop the process.
Cont Default action is to continue the process if it is currently
stopped.
:
Running the program, and test
$ ./a.out
Hello SIGINT !
Hello SIGINT !
^C <--- OUCH ! - Got signal - 2
Hello SIGINT !
Hello SIGINT !
Hello SIGINT !
^C
$
Below red ones are command from other terminal. PID is got from ps ax | grep a.out.
$ kill -19 4100 (stop process)
Hello SIGINT !
Hello SIGINT !
[1]+ Stopped ./a.out
$
$ kill -18 4100 (continue process if stopped)
$ Hello SIGINT !
Hello SIGINT !
Hello SIGINT !
Hello SIGINT !
$ kill -2 4100 (keyboard interrupt Ctrl+C)
^C <--- OUCH ! - Got signal - 2
Hello SIGINT !
$ kill -2 4100 (keyboard interrupt Ctrl+C)
[1]+ 中斷 ./a.out
$
$ kill -15 4107 (terminate process)
Hello SIGINT !
Hello SIGINT !
終止 (terminated)
$
$ kill -9 4369 (kill process)
Hello SIGINT !
已砍掉 (killed)
$
.
沒有留言:
張貼留言