Mastodon Politics, Power, and Science: C - Break out of loop

Tuesday, April 24, 2012

C - Break out of loop


This program demonstrates a C programming entering an infinite loop
and then breaking out of that loop using signal handlers and longjmp.

/*
 *Test the procedure to catch a memory exception
 */

#include <sys wait.h>
#include <errno.h>
#include <fcntl.h>
#include <ctype.h>
#include <stdio.h>
#include <signal.h>
#include <setjmp.h>
#include <unistd.h>

sigjmp_buf env;

/*
 *      Handle the SIGALRM signal when a system alarm expires.
 */

void
handle_sigalarm()
{
 siglongjmp(env, 1);
}

/*
 *
 */

int
infinite_loop (){
 while(5);
}

/*
 *      Check the given memory allocation
 * Trap any segmentation faults
 * Return 1 if would have crashed
 * Return 0 if good.
 */

int
call_infinite_loop (){

 volatile int x;
 x = sigsetjmp(env,1);

 alarm(5);

 if (x == 0)
  infinite_loop();

 alarm(0);
}

/*
 *     Initialize the signal handlers for memory faults
 */

void
InitializeSignalHandlers(){

        struct sigaction handle;

        handle.sa_flags = 0;
        handle.sa_handler = handle_sigalarm;

        sigaction(SIGALRM, &handle, NULL);
}

/*
 *     Initialize everything and run the tests.
 */

int
main (){

 InitializeSignalHandlers();

 call_infinite_loop();

 return 0;
}

No comments:

Post a Comment

How Science Makes Simple Ideas Illegible So They Will Read as "Real Science"

 J. Rogers, SE Ohio The Gatekeeping Reflex Einstein said it out loud Einstein criticized his own field in public, and he named the exact ...