Skip to content

Instantly share code, notes, and snippets.

@codedot
Created May 20, 2011
Embed
What would you like to do?
Signal-based Scheduler
CFLAGS = -g
all: sigsched
./sigsched
clean:
-rm -fr sigsched sigsched.dSYM
#include <assert.h>
#include <signal.h>
#include <setjmp.h>
#include <stdlib.h>
#include <unistd.h>
static jmp_buf cont, stop;
static void handler(int sig)
{
static int trigger;
trigger = !trigger;
alarm(3);
if (trigger) {
if (!setjmp(cont))
longjmp(stop, 0);
} else {
if (!setjmp(stop))
longjmp(cont, 0);
}
}
void sigsched(void (*func)(void))
{
signal(SIGALRM, handler);
if (!setjmp(stop)) {
assert(func);
alarm(3);
func();
abort();
}
}
static void foo(void)
{
while (1) {
static const char msg[] = "foo\n";
write(1, msg, sizeof msg);
sleep(1);
}
}
static void bar(void)
{
while (1) {
static const char msg[] = "bar\n";
write(1, msg, sizeof msg);
sleep(1);
}
}
int main(int argc, char *argv[])
{
sigsched(foo);
bar();
abort();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment