当前位置:编程学习 > C/C++ >>

使用alarm和setjmp实现超时控制

[cpp]
#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
#include <unistd.h>  
#include <signal.h>  
#include <setjmp.h>  
 
#define JMP_VALUE 12345  
 
static jmp_buf test_jmp_env; 
 
static void test_alarm(int n) 

    printf("alarm signal:%d\r\n", n); 
    longjmp(test_jmp_env, JMP_VALUE); 

 
void DoSomething() 

    int i = 0; 
    while(1){ 
        printf("%d\r\n", i++); 
        sleep(1); 
    } 

 
void DoSomethingWithTimeout(int nTimeout) 

    __sighandler_t old_handler = signal(SIGALRM, test_alarm); 
 
    alarm(nTimeout); 
 
    int n = setjmp(test_jmp_env); 
    printf("setjmp result:%d\r\n", n); 
 
    if(JMP_VALUE == n){ 
        signal(SIGALRM, old_handler); 
        return; 
    } 
    else if(0 == n) 
    { 
        DoSomething(); 
        alarm(0); 
        signal(SIGALRM, old_handler); 
    } 
    else 
    { 
        printf("error\r\n"); 
        exit(-1); 
    } 

 
int main(void) 

    DoSomethingWithTimeout(5); 
 
    printf("go on to do...\r\n"); 
 
    return 0; 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <setjmp.h>

#define JMP_VALUE 12345

static jmp_buf test_jmp_env;

static void test_alarm(int n)
{
 printf("alarm signal:%d\r\n", n);
    longjmp(test_jmp_env, JMP_VALUE);
}

void DoSomething()
{
 int i = 0;
 while(1){
  printf("%d\r\n", i++);
  sleep(1);
 }
}

void DoSomethingWithTimeout(int nTimeout)
{
 __sighandler_t old_handler = signal(SIGALRM, test_alarm);

 alarm(nTimeout);

 int n = setjmp(test_jmp_env);
 printf("setjmp result:%d\r\n", n);

 if(JMP_VALUE == n){
  signal(SIGALRM, old_handler);
  return;
 }
 else if(0 == n)
 {
  DoSomething();
  alarm(0);
  signal(SIGALRM, old_handler);
 }
 else
 {
  printf("error\r\n");
  exit(-1);
 }
}

int main(void)
{
 DoSomethingWithTimeout(5);

 printf("go on to do...\r\n");

 return 0;
}


 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,