如何执行处理函数接收终止信号前时退出程序" killall"或QUOT;杀-p PID"? [英] How to execute a handler function before quit the program when receiving kill signal from"killall" or "kill -p pid"?

查看:180
本文介绍了如何执行处理函数接收终止信号前时退出程序" killall"或QUOT;杀-p PID"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

pthread_t test_thread;

void *thread_test_run (void *v)
{
    int i=1;
    while(1)
    {
       printf("into thread %d\r\n",i);
       i++; 
       sleep(1);
    }
    return NULL
}

int main()
{

    pthread_create(&test_thread, NULL, &thread_test_run, NULL);


    sleep (20);  


    pthread_cancel(test_thread);

    sleep(100);
    // In this period (before the finish of myprogram),
    // I execute killall to kill myprogram 
    // I want to add a signal handle function to
    // execute pthread_exit() before the program quit

}

我想加入的信号处理函数执行了pthread_exit()程序退出前完成我的code。

I want to complete my code by adding a signal handle function to execute pthread_exit() before the program quit.

怎么办呢?

推荐答案

由于 killall 将信号发送 SIGTERM 按默认情况下,你可以处理这种类型的信号。

Because killall sends the signal SIGTERM by default, you can handle this type of signal.

#include <signal.h>

void handler(int sig)
{
     /* ... */
}

signal (SIGTERM, handler);

这篇关于如何执行处理函数接收终止信号前时退出程序&QUOT; killall&QUOT;或QUOT;杀-p PID&QUOT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆