4

Currently I am using some non-signal safe functions like fprintf, snprintf in my signal handler. But I need to replace it with signal safe functions like write. But the write function only use a buffer, or a non formatted string. Is there any other methods to print formatted string?

shafeeq
  • 1,499
  • 1
  • 14
  • 30
  • see http://stackoverflow.com/a/16891065/2630032 – Stephan Lechner Jan 20 '17 at 09:35
  • You could make your own (very) simpified "snprint" like function that does just what you need (probably just plain and simple `%s` and `%d`). – Jabberwocky Jan 20 '17 at 10:02
  • I am not allowed to use snprintf means, I cannot use its inner function like vsnprintf, etc... as well. So only allowed to the functions mentioned in http://man7.org/linux/man-pages/man7/signal.7.html – shafeeq Jan 20 '17 at 10:49
  • Possible duplicate of [Print int from signal handler using write or async-safe functions](https://stackoverflow.com/questions/14573000/print-int-from-signal-handler-using-write-or-async-safe-functions) – Ciro Santilli OurBigBook.com Sep 20 '17 at 06:46

1 Answers1

2

Set a flag in the signal handler. Then do the writs to file after returning from the signal handler.

static volatile sig_atomic_t sig_rcvd = 0;

void sig_hanlder(int sig)
{
   sig_rcvd = 1;
}

If sig_rcvd is set then do write to file and possibly reset sig_rcvd back to 0. This way you are avoiding calling any async-signal-unsafe functions from a signal handler.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • Nice idea. But unfortunately it's not useful in my case. In my signal handler what happens is only memory cleaning and killing all threads. So it won't return to main function again – shafeeq Jan 20 '17 at 09:39
  • If it's at program exit, then you don't have to kill the threads or cleanup memory (at least, on Linux). So, you don't need a signal handler. – P.P Jan 20 '17 at 09:41
  • 1
    But in between I need to print call stack to a file – shafeeq Jan 20 '17 at 09:50
  • You can still come out of the signal handler (after setting a flag) and then do your callstack printing. For example: `while(true) { /* do things */; if(sig_rcvd) call_func();}` and then `call_func()` can print the callstack and then call exit(). – P.P Jan 20 '17 at 09:54
  • @shaefeeq: just to see if I understand you right - your signal handler will kill all processes, and the code that has been interrupted by the signal will never resume? – Stephan Lechner Jan 20 '17 at 10:14
  • Yes Stephan Lechner.. :) – shafeeq Jan 20 '17 at 10:46