0

I have a question I am writing a code that find the perfect number by brute forcing the algorithm which is required by my assignment. I want to see how far the ranges goes in 15 seconds. I tried using a while loop and an alarm but it seems to not work at all. How would I go from there?

Thanks

Heres my code:

#define _POSIX_SOURCE
#define _BSD_SOURCE

#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

volatile int stop=0;

void sigalrm_handler( int sig ){
    stop = 1;
}

int main(int argc, char **argv){
    struct sigaction sact;
    int num_sent = 0;

    sigemptyset(&sact.sa_mask);
    sact.sa_flags = 0;
    sact.sa_handler = sigalrm_handler;
    sigaction(SIGALRM, &sact, NULL);

    alarm(15);  /* Request SIGALRM in 60 seconds */
    while (!stop) {
        for (;;){
             for (;;){
            }
        }
    }
    printf("%d \n", num_sent);

    exit(0);
}
false
  • 10,264
  • 13
  • 101
  • 209
jtd92
  • 359
  • 2
  • 6
  • 16

1 Answers1

0

Even if the alarm gets triggered and set stop to a non-zero value you won't notice since your for loop doesn't return to the outer while. You need to apply the condition to all loops that should be stopped:

while (!stop) {
    for (;!stop;){
         for (;!stop;){
        }
    }
}

An alternative to alarm is simply checking whether you crossed a certain timepoint:

time_t end = time(0) + 15;
while (end < time(0)) {
    for (;end < time(0);){
         for (;end < time(0);){
        }
    }
}
Zeta
  • 103,620
  • 13
  • 194
  • 236
  • If I have bounds like for (i = 0; i++;), should I do like an if statement with a break in it? if (!stop) break; ? – jtd92 Mar 10 '13 at 07:42
  • @user2076354: transform `for(init; cond; inc)` to `for(init; cond && !stop; inc)` – Zeta Mar 10 '13 at 07:43