zoukankan      html  css  js  c++  java
  • [linux] C语言Linux系统编程-捕获进程信号

    typedef void( *sighandler_t)(int);

    1.typedef给类型起一个别名。

    2.为函数指针类型定义别名,

    3.函数指针(指向函数的指针)

    sighandler_t signal(int signum, sighandler_t handler);

    1.函数原型

    2.使用自定义的类型别名,作为函数参数和函数返回值

    3.第一个参数是信号的标号,第二个参数是函数指针

    implicit-function-declaration(不明函数声明)

    sleep()函数在#include<unistd.h>这个头文件中

    #include <stdio.h>
    #include <signal.h>
    #include<unistd.h>
    //申明一个自定义函数
    void myHandler(int signum){
            printf("捕获到信号 %d 
    ",signum);
    }
    int main(){
            //定义一个函数指针,指向上面的函数
            void(* handler)=myHandler;
            //调用函数,传递参数int信号标号,传递函数指针
            signal(SIGINT,handler);//捕获ctrl+c
            signal(SIGTERM,handler);//捕获程序退出
            while(1){
                    printf("进程运行中...
    ");
                    sleep(1);
            }   
    }
    

    运行结果:

    信号2是我ctrl+c  , 信号15是我kill 进程id  ,   但是当我kill -9 进程id时 , 使用signal(SIGKILL,handler) 信号不能被捕获

    进程运行中...
    进程运行中...
    进程运行中...
    ^C捕获到信号 2
    进程运行中...
    进程运行中...
    进程运行中...
    捕获到信号 15

      

  • 相关阅读:
    Gym 101606 F-Flipping Coins(概率dp)
    Gym101350 J Lazy Physics Cat
    Gym 101350G
    hdu6188 Duizi and Shunzi (贪心或者dp)
    Gym101350 FMonkeying Around
    codeforce 457DIV2 C题
    codeforce 457DIV2 B题
    codeforce 461DIV2 F题
    codeforce 461DIV2 E题
    PE文件RV转FOA及FOA转RVA
  • 原文地址:https://www.cnblogs.com/taoshihan/p/8045159.html
Copyright © 2011-2022 走看看