alarm function

Asked 2 weeks ago, Updated 2 weeks ago, 1 views

I have a question. The desired value is running every 5 seconds...That's how it's written If you write the code and the name is alarm.c, if you do alarm 5, the value of *argv[1] goes to 5 If we execute it, wouldn't SIGALARM be executed on signal after 5 seconds through alarm (*argv[1]) in the main function and exit (0)? Why does running keep coming out when I run it and it can't end...

include stdio.h

include stdlib.h

include signal.h

include unistd.h

void sig(int signal)

{

exit(0);

}

int main(int argc, char *argv[])

{

signal(SIGALRM, sig);

alarm(*argv[1]);

while(1){

    printf("running...\n");

    sleep(1);

    }

return 0; }

unix

2022-09-20 13:31

1 Answers

alarm(unsigned) accepts unsigned integers as call factors.

*argv[1] is treated as an integer as char. When executed with ./alarm5, the iskey code 53 for '5' instead of an integer 5.

That is, alram (*argv[1]) generates a signal after 53 seconds.

Therefore, you should call it by converting a string into an integer, as follows:

int main(int argc, char *argv[])
{
  int timeout = atoi(argv[1]);
  if (timeout < 0)
    return -1;

  signal(SIGALRM, sig);
  alarm((unsigned) timeout);

As an admonition, exit() should not be used in the signal handler. Please refer to the following link.

https://en.cppreference.com/w/c/program/signal#Signal_handler


2022-09-20 13:31

If you have any answers or tips


© 2022 pinfo. All rights reserved.