I want to handle a kill signal
from C program. I'm starting by create an infinite loop and handle the signal
void signal_callback_handler(int signum)
{
printf("Caught signal %d\n",signum);
// Cleanup and close up stuff here
// Terminate program
exit(signum);
}
main()
{
signal(SIGINT, signal_callback_handler);
printf("pid: %d \n",getpid());
while(1)
{
}
}
When I run this program and make CTRL+C, the kill is handled, and it works. The message Caught signal
is printed. However, when I'm trying to kill from another program
int main(int argc, char **argv)
{
kill(atoi(argv[1]), SIGKILL);
return 0;
}
The program is stoped but the signal is not handled. In other words, the message Caught signal
is not printed. The infinite loop is just stopped.
就是这样:您无法捕获SIGKILL
,它肯定会杀死您的程序,这就是它的创建目的。
You cannot catch or ignore a SIGKILL signal. Also in your code shown below you have created a signal handler only for SIGINT, that is, whenever a SIGINT signal is caught it will call the signal_callback_handler(). All other signals will be caught by the default signal handler.
signal(SIGINT, signal_callback_handler);
For example if you want to catch a SIGHUP signal also in the your program you need to define a signal handler as below:
signal(SIGHUP, signal_callback_handler);
Modified code is shown below:
void signal_callback_handler(int signum)
{ if (signum == SIGINT){
printf("Caught signal %d\n",signum);
//Do the action need to be taken when SIGINT is received
}
else if(signum == SIGHUP){
printf("Caught signal %d\n",signum);
//Do the action need to be taken when SIGHUP is received
}
}
int main()
{
signal(SIGINT, signal_callback_handler);
signal(SIGHUP, signal_callback_handler);
printf("pid: %d \n",getpid());
while(1)
{
}
return 0;
}
You need to add
signal(SIGTERM, signal_callback_handler);
As you are only connected to SIGINT (eg Ctrl+C) but for a kill/killall your friend is SIGTERM
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.