zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    word2vec
    视频推荐系统
    python基础
    go-elasticsearch
    Docker 部署 go项目
    gohbase
    禅道部署linux
    jmeter 报错 Error occurred during initialization of VM Could not reserve enough space for object heap
    jarvis OJ-DSA
    算法-我的第一本算法书(一)
  • 原文地址:https://www.cnblogs.com/dong1/p/14040136.html
Copyright © 2011-2022 走看看