繁体   English   中英

C linux信号和功能

[英]C linux signals and functions

我遇到了这个问题,下面将对其进行简化:

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

int main(void) {
    signal(SIGALRM, &INThandler);

    //get menu options which Im not going to put here
    game(...stuff...);
}

void game(..stuff...) {
    //do the game stuff AND set an alarm()
}

void INThandler(int sig) {
    system("clear");
    printf("Time is up!\n");
    //I WANT game() TO STOP WHICH WILL EXIT TO MAIN WHERE MORE STUFF IS HAPPENING
}

在game()中,我有

while(counter <= amount)

因此,我想将变量计数器和数量传递给INThandler,以便可以更改它们,以便条件为假,但是仅在警报为0时才调用INThandler,而不使用参数来调用。 game()继续,但我不想这么做。 如果有更好的方法,请告诉我。

使用全局变量作为计数器和数量?

当调用一个函数并且该函数中包含变量时,这些变量将分配在堆栈上。 如果定义全局变量,则将在程序加载时分配它。 您的信号处理程序应有权访问这些变量。

#include <stdio.h>
#include <signal.h>
#include <stdlib.h> //Also include this, needed for exit(returncode)

int counter; //Not inside any function
int amount;  //All functions may access these

int main(void) {
    signal(SIGALRM, &INThandler); 

    //get menu options which Im not going to put here
    game(...stuff...);
}

void game(..stuff...) {
    //do the game stuff AND set an alarm()
}

void INThandler(int sig) {
    //Do stuff with counter and amount
    //system("clear"); I recommend that you do not use system to clear the screen, system(command) is inefficient.
    printf("\033[H\033[JTime is up!\n");
    //Do that extra stuff you want to do in main here, then
    exit(0);
}

另一个注意事项:根据Linux编程手册中的signal(2):

signal()的唯一可移植用法是将信号的处置方式设置为SIG_DFL或SIG_IGN。 使用signal()建立信号处理程序时的语义在系统之间有所不同(而POSIX.1明确允许这种变化); 请勿将其用于此目的。

POSIX.1通过指定sigaction(2)解决了可移植性问题,当调用信号处理程序时,它提供了对语义的显式控制。 使用该接口而不是signal()。

要使用sigaction注册信号处理程序,

#include <signal.h>

int main(){
    const struct sigaction saSIGALRM = {
        .sa_handler = mySignalHandler, //replace this with your signal handler, it takes the same parameters as using signal()
    };
    sigaction(SIGALRM, &saSIGALRM, 0);
}

它比看起来简单。 请记住,由于编程效率低下,今天的计算机速度很慢。 请,请,请使用高效的程序。

点击这里查看更多很酷的事情的sigaction可以做,以为什么不使用信号沿()

暂无
暂无

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

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