c - 使用 sigaction() 实现 siginterrupt()?

标签 c linux

通过一个示例使用 sigaction() 实现 siginterrupt()

#define _XOPEN_SOURCE 700

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

void helpAndLeave(const char *progname, int status);
void pexit(const char *fCall);
int interrupt(int, int);
void handler(int);

int main(int argc, char *argv[]) {
    if (argc != 1) {
        helpAndLeave(argv[0], EXIT_FAILURE);
    }

    /* struct sigaction act;
       act.sa_handler = &handler;
     */

    interrupt(2,1);
//  while(1);

    exit(EXIT_SUCCESS);
}

void helpAndLeave(const char *progname, int status) {
    FILE *stream = stderr;

    if (status == EXIT_SUCCESS) {
        stream = stdout;
    }

    fprintf(stream, "Usage: %s", progname);
    exit(status);
}

void pexit(const char *fCall) {
    perror(fCall);
    exit(EXIT_FAILURE);
}

int interrupt(int signal, int flag) {

    printf("interrupt block\n");
    struct sigaction act;
    act.sa_handler = &handler;

    if (sigaction(SIGINT, NULL, &act) == -1) {
        return -1;
    }

    if (flag) {
        act.sa_flags &= ~SA_RESTART;
    } else {
        act.sa_flags &= SA_RESTART;
    }

    if (sigaction(SIGINT, &act, NULL) == -1) {
        printf("sigaction error\n");
        return -1;
    }
    printf("exit occur\n");
    while(1);
}

void handler(int signal) {
    printf("OMG, INTERRUPTION!!!!!\n");
}

这里当我输入 (ctrl+c) 时它不会处理函数。

所以请给出一些解决方案。

你可以在 this link 上找到这个例子.

最佳答案

当您调用 sigaction(SIGINT, NULL, &act) 时,它会用信号的当前处理程序覆盖 act。所以你对 act.sa_handler 的分配被覆盖了。您需要在通话之后完成该作业,而不是在通话之前。

在位掩码中打开位的方法是使用|,而不是&,所以

    act.sa_flags &= SA_RESTART;

应该是:

    act.sa_flags |= SA_RESTART;

所以整个函数应该是:

int interrupt(int signal, int flag) {

printf("interrupt block\n");
struct sigaction act;

if (sigaction(SIGINT, NULL, &act) == -1) {
    return -1;
}

act.sa_handler = &handler;

if (flag) {
    act.sa_flags &= ~SA_RESTART;
} else {
    act.sa_flags |= SA_RESTART;
}

if (sigaction(SIGINT, &act, NULL) == -1) {
    printf("sigaction error\n");
    return -1;
}
printf("exit occur\n");
while(1);
}

关于c - 使用 sigaction() 实现 siginterrupt()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39265386/

相关文章:

c - 声明长度为 [x] 个字符的 Char 数组

android - 为 Android 编译 Lua lib - 成功,但奇怪的段错误

linux - 如何找出 Linux 中哪些进程正在使用交换空间?

php 页面未在/usr/local/中打开

c++ - 可以在函数名上使用#ifndef 吗?

C - 如何将 char(8 位) 转换为 ascii 格式

c - Malloc 改变 C 中的值

linux - CMake:如何在安装之前执行命令?

python - 复制 Python 子进程的终端输出

linux - Cronjob 运行时返回错误