2
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
using namespace std;

int count = 0; 

void alarm2(int signo)
{
    cout << count;
}

void alarm1(int signo)
{
    signal(SIGALRM, alarm2);
    cout << "ctrl+C";
    alarm(10);
    sleep(10);
}

int main()
{
    signal(SIGALRM, alarm1);

    alarm(3);
    sleep(5);
}

I want that after 3 seconds I get the message "ctrl+C" and then another alarm set for 10 seconds; after that I should get the value of count. But when I run after just 10 sec I get "ctrl+C" and the value of count.

Hasturkun
  • 35,395
  • 6
  • 71
  • 104
  • Use pause(), don't tag C#, don't use cout in signal handler. – Grijesh Chauhan Jul 14 '13 at 11:24
  • why should i not use cout and where i use pause() – Usman Nazir Jul 14 '13 at 11:27
  • You aren't sending a newline after your `cout` call, and you aren't explicitly flushing the output... you only see the output later because your program terminates causing the buffer to flush. Furthermore, the sleep within your first signal handler is a terrible thing to do; get rid of it! (Perhaps move it into main). – mah Jul 14 '13 at 11:34
  • I didn't find any link for c++ but you may get an idea from this [Q&A](http://stackoverflow.com/questions/16891019/how-to-avoid-using-printf-in-a-signal-handler) in C – Grijesh Chauhan Jul 14 '13 at 11:35
  • i have move sleep to main still no progress – Usman Nazir Jul 14 '13 at 11:48

2 Answers2

1

In your example you made many, many mistakes.

First of all look at documentation about which function is safe to call from signal handlers: https://www.securecoding.cert.org/confluence/display/seccode/SIG30-C.+Call+only+asynchronous-safe+functions+within+signal+handlers

Of course functions that can allocate memory is not safe to call, because of it is not safe to call malloc. Because of it is not right to call printf or std::ostream::opeartor<< (std::cout <<) in signal handler.

Second, in documentation (type man 3 sleep) clearly written it is not safe mix sleep and alarm,

Third you not wait enough in main function, so it can exit before the second alarm handler run.

Here is how it can be done:

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

volatile sig_atomic_t done = 0;

void alarm2(int signo)
{
    write(STDOUT_FILENO, "alarm2\n", sizeof("alarm2\n") - 1);
    done = 1;
}

void alarm1(int signo)
{
  signal(SIGALRM, alarm2);
  write(STDOUT_FILENO, "ctrl+C\n", sizeof("ctrl+C\n") - 1);
  alarm(10);
}

int main()
{
  signal(SIGALRM, alarm1);

  alarm(3);

  while (done == 0)
    sleep(1); //sleep can be wake up by alarm signal, so check flag    
}
fghj
  • 8,898
  • 4
  • 28
  • 56
0

Add "<< endl;" to all your cout statements and try again.

ROTOGG
  • 1,106
  • 1
  • 7
  • 17