I am doing something like this:
#include <signal.h>
class myClass {
public:
void myFunction ()
{
signal(SIGIO,myHandler);
}
void myHandler (int signum)
{
/**
* Handling code
*/
}
}
I am working on Ubuntu, using gcc.
But it won't compile. It is complaining with:
error: the argument with type
void (MyClass::)(int)
doesn't agree withvoid (*) (int)
Any clues? Or maybe it is just that I cannot use a signal inside classes? Are signals only allowed in C?
The error message is an approximate translation because my compiler is not in English.
The second parameter of signal should be a pointer to a function accepting an int and returning void. What you're passing to signal is a pointer to a member function accepting an int and returning void (its type being
void (myClass::*)(int)
). I can see three possibilities to overcome this issue:1 - Your method
myHandler
can be static: this is great, make it static2 - Your method shouldn't be static: if you're planning to use signal with only one instance, you can create a private static object, and write a static method that simply call the method on this object. Something along the lines of
3 - However, if you're planning on using the signal with multiple instances, things will get more complicated. Perhaps a solution would be to store each instance you want to manipulate in a static vector, and invoking the method on each of these :
and somewhere, do a single call to
But I think that if you end up using the last solution, you should probably think about changing your handling design :-)!
It does seem crazy that you can post new answers with less reputation than it takes to comment on existing ones, but there we go.
gekomad's answer from Sept 24 2015 was the one that I used to solve my problem. It is worth pointing out that this will only work completely obviously when there is only ever one instance of
myClass
created. otherwise, the static object pointer will point to one of the instances (the most recently created) which may not be the desired one.And, in case it is useful to someone else, a valid 2018 URL for the FAQ question linked in a couple of the answers is:
http://www.cs.technion.ac.il/users/yechiel/c++-faq/memfnptr-vs-fnptr.html
To pass a pointer to a method, it must be a static method and you must specify the class name.
Try this:
And you should also read the link supplied by Baget, the paragraph 33.2 in the C++ FAQ.
Read this following section (33.2):
C++ FAQ - pointers-to-members
Actually, C++ signal handlers are not permitted to use any facilities not present in both C and C++ (except that in C++11 they may use atomics), and are required to use C linkage. Quoting C++11 draft n3242 section 18.10 "Other runtime support" [support.runtime] (paragraph 8),
(Clause 29 being the one on atomics.)