Thomas131
Thomas131

Reputation: 131

C/C++: calling a function on exit with sigaction() doesn't work

I've this code:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <wiringPi.h>
#include <signal.h>

void exfunc(sig_t s) {
    ...
    exit(1);
}

int main(void) {
    ...
    sigaction(SIGINT,exfunc);
    ...
}

And when I try to compile this code, I get the following error:

main.cpp: In function 'int main()':
main.cpp:36:25: error: cannot convert 'void (*)(sig_t) {aka void (*)(void (*)(int))}' to 'const sigaction*' for argument '2' to 'int sigaction(int, const sigaction*, sigaction*)'

I can't find the mistake. What did I do wrong? I'm new in programming in C/C++.

Upvotes: 0

Views: 1234

Answers (1)

Bill Door
Bill Door

Reputation: 18926

You probably want to use signal instead of sigaction. signal is the simplified version of sigaction.

signal(SIGINT, exfunc);

Using sigaction requires that an array of elements be defined. Useful if you wish to install several signal handlers. A lot of work if you only want one. sigaction also allows access to the many features of signals. signal is simplified and generally does what one would expect.

exfunc also has the wrong prototype. sig_t is the typedef for the function proto type:

typedef void (*sig_t)(int);

This reads, sig_t is a function that takes an int parameters and returns void. Change exfunc to

void exfunc(int s) {

will allow your program to compile.

Upvotes: 2

Related Questions