• Handle a signal & clock()


    C

    Library: POSIX

    Standard C's sleep() only provides one-second resolution, so the POSIX usleep() function is used here. (POSIX is not needed for the actual signal handling part.)

    #include <stdio.h>
    #include <stdlib.h> // for exit()
    #include <signal.h>
    #include <time.h> // for clock()
    #include <unistd.h> // for POSIX usleep()
     
    volatile sig_atomic_t gotint = 0;
     
    void handleSigint() {
    /*
    * Signal safety: It is not safe to call clock(), printf(),
    * or exit() inside a signal handler. Instead, we set a flag.
    */
    gotint = 1;
    }
     
    int main() {
    clock_t startTime = clock();
    signal(SIGINT, handleSigint);
    int i=0;
    for (;;) {
    if (gotint)
    break;
    usleep(500000);
    if (gotint)
    break;
    printf("%d ", ++i);
    }
    clock_t endTime = clock();
    double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
    printf("Program has run for %5.3f seconds ", td);
    return 0;
    }
    Output:
    1
    2
    3
    Program has run for 1.953 seconds
    

    copyright

    https://rosettacode.org/wiki/Handle_a_signal#C

    ### other signal

    void __sigroutine( int p_iSigNum )
    {
        switch( p_iSigNum )
        {
        case SIGHUP:
        case SIGINT:
        case SIGQUIT:
        case SIGTERM:
            _bStop = true;
            printf("recv signal %d
    ", p_iSigNum);
            break;
    
        default:
            break;
        }
    }
    
    bool __init_capture()
    {
        if( SIG_ERR == signal( SIGHUP, __sigroutine ) )
        {
            printf("signal SIGHUP failed
    ");
            return false;
        }
    
        if( SIG_ERR == signal( SIGINT, __sigroutine ) )
        {
            printf("signal SIGINT failed
    ");
            return false;
        }
    
        if( SIG_ERR == signal( SIGQUIT, __sigroutine ) )
        {
            printf("signal SIGQUIT failed
    ");
            return false;
        }
    
        if( SIG_ERR == signal( SIGTERM, __sigroutine ) )
        {
            printf("signal SIGTERM failed
    ");
            return false;
        }
    
        return true;
    }
  • 相关阅读:
    HTTP协议抓包分析
    cmd 中使用 tracert
    Ubuntu 搭建zabbix
    kerberos+ldap
    运行程序显示丢失“MSVCR100D.dll”
    熊猫烧香病毒样本分析
    Masm32sdk安装指南
    16位汇编实现三大基本排序
    逆向工程初步160个crackme-------3
    一个入门级CTF的Reverse
  • 原文地址:https://www.cnblogs.com/dong1/p/14040136.html
Copyright © 2020-2023  润新知