Question

I have a program that is supposed to take in 3 different arguments from the command line. The third argument is the only argument that is passed into the alarm function. For example, if my program is called BuzzOff this is how it would work:

$ BuzzOff 10 99999 1

The third argument is 1 so 1 will be passed into the alarm function. My program should be printing out the variable total's value every arg3 seconds. In this case every 1 second. However, when I tried to use 1 as my third argument, the alarm takes much longer than 1 second. It takes about 14 seconds. It seems to print at the same rate no matter what I use as my arg3. Am I implementing the alarm function correctly?

Here is my code:

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

double arg1, arg2, arg3;
double total = 0;
int debug = 0;

void sigusr1_handler(int signo)
{
    if (signo == SIGUSR1)
      printf("total: %f\n", total);
}
void sigusr2_handler(int signo)
{
    if (signo == SIGUSR2)
      debug = ((debug == 1) ? 0 : 1);
}
void sigint_handler(int signo)
{
  if (signo == SIGINT)
    {
      printf("total: %f\n", total);
      exit(0);
    }
}
void sigalrm_handler(int signo)
{
  if (signo == SIGALRM)
    {
      printf("total: %f\n", total);
      signal(SIGALRM, sigalrm_handler);
      alarm(arg3);
    }
}

int main(int argc, char *argv[])
{
    if( argc!=4 ) {
        printf("need three arguments\n"); return(1);
    }
    arg1 = (double) atoi(argv[1]);
    arg2 = (double) atoi(argv[2]);
    arg3 = (double) atoi(argv[3]);

    double count;

    signal(SIGUSR1, sigusr1_handler);
    signal(SIGUSR2, sigusr2_handler);
    raise(SIGUSR2);
    if (debug == 1)
      {
    signal(SIGUSR1, SIG_IGN);
    signal(SIGALRM, sigalrm_handler);
    alarm(arg3);
      }
    else if (debug == 0)
      {
    signal(SIGUSR1, sigusr1_handler);
    signal(SIGINT, sigint_handler);
      }
    for (count = 0; count < arg2; count += 0.001)
      {
    total += count*arg1;
      }
    return 0;

}
Was it helpful?

Solution

You convert your input to a double, but the alarm() functions expects an unsigned int. No idea what the bit pattern of the lower (upper) half of a 1.0 is, but I would not be surprised if it comes out as 14.

Does the compiler not complain about passing the double arg3 into alarm()?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top