Linux信号与定时器应用实例训练


/* 信号处理函数 */

static void SigHandler(int signo)

{

    /* 变量声明 */

    struct itimerval tmp_itimer;

    struct timeval realtv, cputv, usertv, kerneltv;


    /* 获得实时定时器时间 */

    getitimer(ITIMER_REAL, &tmp_itimer);

    TimerPassed(&tmp_itimer, &realtv);


    /* 获得CPU定时器时间 */

    getitimer(ITIMER_PROF, &tmp_itimer);

    TimerPassed(&tmp_itimer, &cputv);


    /* 获得用户定时器时间 */

    getitimer(ITIMER_VIRTUAL,&tmp_itimer);

    TimerPassed(&tmp_itimer, &usertv);


    /* 计算Linux内核使用CPU时间 */

    TimeSubstract(&cputv, &usertv, &kerneltv);

/* 按照信号进行处理 */

    switch (signo)

    {

    /* 用户信号1 */

    case SIGUSR1:

        /* 输出各种时间值 */

        PrintTimeval("Real Time ", &realtv);

        PrintTimeval("CPU Time   ", &cputv);

        PrintTimeval("User Time ", &usertv);

        PrintTimeval("Kernel Time", &kerneltv);

        printf("\n");

        break;


    /* 定时器信号 */

    case SIGALRM:

        /* 输出时间值后退出程序 */

        printf("Time up, the application will escape.\n");

        PrintTimeval("CPU Time   ", &cputv);

        PrintTimeval("User Time ", &usertv);

        PrintTimeval("Kernel Time", &kerneltv);

        exit(0);

        break;

    }

}


/* 计算时间的流逝 */

void TimerPassed(const struct itimerval *itimer, struct timeval *tv)

{

    TimeSubstract(&(itimer->it_interval), &(itimer->it_value), tv);

}


/* 计算两个时间的差值 */

void TimeSubstract(const struct timeval *tv1, const struct timeval *tv2, struct timeval *tvres)

{

    /* 变量声明 */

    const struct timeval *tmptv1, *tmptv2;

    int cmpres;


    /* 比较tv1和tv2,将较大值赋给tmptv1,较小值赋给tmptv2 */

    cmpres = TimeCompare(tv1, tv2);

    if (cmpres > 0) {

        tmptv1 = tv1;

        tmptv2 = tv2;

} else {

        tmptv1 = tv2;

        tmptv2 = tv1;  

    }


    /* 做差时存在借位的情况 */

    if (tmptv1->tv_usec < tmptv2->tv_usec) {

        /* 结果的秒数多减1,借给微秒 */

        tvres->tv_sec = tmptv1->tv_sec - tmptv2->tv_sec - 1;

        /* 微秒做减法时,先加上借来的一秒(1000000微秒) */

        tvres->tv_usec = tmptv1->tv_usec + 1000000 - tmptv2->tv_usec;

    /* 不存在借位的情况 */

    } else {

        /* 对应的秒和微秒分别做差 */

        tvres->tv_sec = tmptv1->tv_sec - tmptv2->tv_sec;

        tvres->tv_usec = tmptv1->tv_usec - tmptv2->tv_usec;

    }

}


/* 时间值比较大小 */

int TimeCompare(const struct timeval *tv1, const struct timeval *tv2)

{

    /* 如果秒值不一致则秒值大者较大 */

    if (tv1->tv_sec > tv2->tv_sec)

        return 1;

    else if (tv1->tv_sec < tv2->tv_sec)

        return -1;

    /* 秒值相同的,微秒值较大者较大 */

    else if (tv1->tv_usec > tv2->tv_usec)

        return 1;

    else if (tv1->tv_usec < tv2->tv_usec)

        return -1;

    /* 秒值和微秒值皆相同者等值 */

    else

        return 0;

}


/* 打印时间 */

void PrintTimeval(const char *str, const struct timeval *tv)

{

    printf("%s = %ld sec %ld usec\n", str, tv->tv_sec, tv->tv_usec);

}

程序会提示你输入空循环的次数,2.7GHz的CPU在空闲的时候使用300至500时大约会1秒钟显示一次时间。数值越大显示时间的间隔越长,根据你的计算机的具体情况而定。此外输出的数据也各你当前系统状态而定。结果如图所示。

 

相关内容