Im building a simple task switcher that runs two functions in a loop. The idea is that it runs a f1 for an amount of time and then gives control to f2 for the same amout, then f1, f2, in an endless loop.
The problem is that whenever i run the program, the first switch goes well but the following switches never happen. Getting stuck in f2.
Ive tried other implementations archieving 3 switches at most (with the program getting frozen after that).
This is my current implementation:
#include <stdio.h>
#include <signal.h>
#include <sys/time.h>
#include <unistd.h>
int count = 0;
int flag = 0;
void f1() {
for (;;) printf("A");
}
void f2() {
for (;;) printf("B");
}
void sched() {
flag = !flag;
if (flag)
f1();
else
f2();
}
void sighandler(int signo)
{
printf("signal %d occurred %d times\n",signo, ++count);
sched();
}
int main(void)
{
struct itimerval it;
struct sigaction act, oact;
act.sa_handler = sighandler;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(SIGPROF, &act, &oact);
it.it_interval.tv_sec = 0;
it.it_interval.tv_usec = 10000;
it.it_value.tv_sec = 0;
it.it_value.tv_usec = 10000;
setitimer(ITIMER_PROF, &it, NULL);
sched();
}
Any suggestion would be greatly appreciated.
Your signal handler calls sched()
, which never returns (but ends up in either of the for (;;)
loops). So after the first switch, you are always inside the signal handler, and further signals are masked.