Use alarm and setjmp for timeout Control

Source: Internet
Author: User

[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;
}


 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.