python/java/c等程序退出钩子函数

python

import atexit
import time

atexit.register(lambda x, y: print("shutdown:", x + y), x=1, y=2)
if __name__ == '__main__':
    time.sleep(10)
    print("hi")

java

public class ShutdownHook {
    static {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("shutdown");
        }));
    }
    public static void main(String[] args) throws InterruptedException {
        System.out.println("hi");
        TimeUnit.SECONDS.sleep(10);
    }
}

C

main函数正常或异常退出时调用(exit调用时就相当于main退出),不响应ctrl+c,kill等发出的信号

#include 
#include 
#include 

void cleanup(){
    printf("shutdown_hook");
}

int main() {
    atexit(cleanup);
    printf("hi\n");
    exit(1);
    sleep(10);
    return 0;
}

捕捉ctrl+c等发出的信号

#include 
#include 
#include 

void mySigAction(int num){
    printf("sigint is:%d\n",num);
}

int main(int argc, char* argv[]) {
    signal(SIGINT, mySigAction);
    printf("hi\n");
    sleep(10);
    return 0;
}

你可能感兴趣的:(python,java,c语言)