C++ Signal Handling

Programming, for all ages and all languages.
Post Reply
User avatar
Neo
Member
Member
Posts: 842
Joined: Wed Oct 18, 2006 9:01 am

C++ Signal Handling

Post by Neo »

Following Solar's advice (from this thread) I included the <csignal> in my class header file and then tried to redirect the SIGALRM to a class member function.
But i keep getting an error saying that
error: argument of type `void (ClientSocket::)(int)' does not match `void*'
where 'ClientSocket' is the name of my class.
What is the right way to get my C++ member functions to be called on interrupt signals?
Only Human
User avatar
Candy
Member
Member
Posts: 3882
Joined: Tue Oct 17, 2006 11:33 pm
Location: Eindhoven

Re:C++ Signal Handling

Post by Candy »

the void (ClientSocket::)(int) indicates you have a "Member Function Pointer", for which you need an object to call it on. You cannot pass an object along with it just like that, you need a normal "Function Pointer". You can do that with a static member, by allowing it to use a static pointer to your object or something similar. A static member is similar to a normal C function.

These functions were never written with C++ in mind. Don't try to use them without the glue designed for it.
User avatar
Neo
Member
Member
Posts: 842
Joined: Wed Oct 18, 2006 9:01 am

Re:C++ Signal Handling

Post by Neo »

I tried the following out but get a linker error

Code: Select all

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

class A{
  static int Timeout;
 public:
  A()
  {
   signal(SIGALRM,Alarm);
  }
  static void Alarm(int signum)
  {
    Timeout++;
    cout<<"In alarm handler"<<endl;
  }
  void Test()
  { 
    cout<<"In Test()"<<endl;
    alarm(4);
    while(!Timeout);
    cout<<"Leaving Test"<<endl;
  }
};

main()
{
  A a;
  a.Test();
}
Only Human
zloba

Re:C++ Signal Handling

Post by zloba »

I tried the following out but get a linker error

Code: Select all

static int Timeout;
you also have to declare it outside the class body like so:

Code: Select all

class A{
  static int Timeout;
...
}

int A::Timeout; // <- you need this
Post Reply