Why Signal is Dangerous

Seems this title is also dangerous, aha, this is a long story, some time ago, I want to implement a timer logic(when timer trigger, run some logic), but I don’t want to create a new thread, so I remember the signal, and then someone warning me maybe it’s not safe. I don’t know why, he only told me that it’s not recommend.

Ok, this is a question around my mind for a long time, I want to know why, but most of all articles couldn’t explain the reason clearly. I need to figure it out by myself. So this is why I write this blog.

Some days ago, I took some time to read this article, and I got some conclusions which can explain my questions:

  • Signal handler need as simple as possible, don’t use non-reentry function in it. for example the fprintf api may involve in this issue.
  • Signal handler also will break lock, because it doesn’t care which part was locked. So this may cause dead lock.
  • Signal may merged by kernel, so we can’t use signal to do some statistic.

Ok, I just listed some major points, so we can use the signal to do some simple purpose, write the simple logic in it. That will be safe, for example, we only update a flag in signal handler. 😀

Ok, all above, I just described the origin signal usage, for now, we have the signalfd api to create a fd which can poll for monitoring, but you need to investigate whether you can add this fd to your polling list, because this part may inside in your framework which you can’t control it. This method can solve the 1 and 2 issues above.

Have a fun. 😀

%d bloggers like this: