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