简体   繁体   English

C / C ++:使用sigaction()在exit上调用函数不起作用

[英]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++. 我是C / C ++编程的新手。

You probably want to use signal instead of sigaction. 您可能希望使用信号而不是sigaction。 signal is the simplified version of sigaction. signal是sigaction的简化版本。

signal(SIGINT, exfunc);

Using sigaction requires that an array of elements be defined. 使用sigaction需要定义一个元素数组。 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. sigaction还允许访问信号的许多功能。 signal is simplified and generally does what one would expect. 信号被简化并且通常做到人们期望的。

exfunc also has the wrong prototype. exfunc也有错误的原型。 sig_t is the typedef for the function proto type: sig_t是函数proto类型的typedef:

typedef void (*sig_t)(int);

This reads, sig_t is a function that takes an int parameters and returns void. 这个读取,sig_t是一个接受int参数并返回void的函数。 Change exfunc to exfunc更改为

void exfunc(int s) {

will allow your program to compile. 将允许您的程序编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM