Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Signal handling in C++

Argument of type void (*)(int) is incompatible with parameter of type __sighnd64_t

Below is my simple code:

#include <iostream>
#include <string>
#include <signal.h>
#include <ctype>
#include <stdlib.h>
#include <stdio.h>
typedef struct mystrcut
{

  int a;
  char *b;

} mystr;

void set_string ( char **, const char * );
void my_handler(int s)
{
    printf("Caught signal %d\n",s);
    exit(1);

}

int main()
{
    const std::string str1[] = {"hello1", "hello2"};
    char str2[50];
    size_t size1 = str1[1].size();
    cout << size1;
    memcpy (str2, str1[1].c_str(), size1);

    cout << str2;
    mystr *m = NULL;
    m = new mystrcut;
    m->a = 5;

    set_string(&m->b, "hello");

    cout << m->b;
    delete []m->b;
//    void (*prev_fn)(int);
    signal (SIGINT,my_handler);
    return 0;
}
void set_string ( char **a, const char *b)
{
    *a = new char [strlen(b)+1];
    strcpy (*a, b);
}

I am working on openvms. Can I avoid the compilation error by some kind of type casting? My compiler expects `__sighnd64_t __64_signal(int, __sighnd64_t);

Adding around the handler extern c has worked. Thanks

like image 232
Sam Avatar asked Oct 11 '22 15:10

Sam


1 Answers

Signal handling is not a C++, but a C. This error is bit strange...

In such cases, try to use extern "C" around your handler (to define it as C function), as https://stackoverflow.com/users/775806/n-m said in comments. Modern <signal.h> from openvms already has extern "C" inside: http://wasd.vsm.com.au/conan/sys$common/syslib/decc$rtldef.tlb?key=SIGNAL&title=Library%20/sys$common/syslib/decc$rtldef.tlb&referer=http%3A/wasd.vsm.com.au/conan/sys$common/syshlp/helplib.hlb.

HP docs says only about C, not a C++.

Another doc says that signal handler (catcher) must be declared in C as

 void func(int signo);
like image 88
osgx Avatar answered Oct 14 '22 04:10

osgx