我有以下代码。当我在睡觉时收到SIGINT时如何将控件带回cleanupCode()?我不想使用goto或jump。在处理程序内部调用cleanupCode不是一个选项。
sigHandler(int sig __atribute__((unused)) {
loopFlag = 0;
}
void cleanupCode()
{ printf("Graceful exit \n");
}
int main () {
while(loopFlag)
sleep(600);
cleanupCode();
}
答案 0 :(得分:5)
你必须在某处设置信号处理程序。
#include <signal.h>
#include <unistd.h>
volatile int loopFlag = 1;
void sigHandler(int sig)
{
loopFlag = 0;
}
void cleanupCode()
{
printf("Graceful exit \n");
}
int main ()
{
signal(SIGINT, sigHandler);
while(loopFlag)
sleep(600);
cleanupCode();
}
答案 1 :(得分:4)
这对我有用:
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
typedef struct sigaction SigAction;
static volatile sig_atomic_t loopFlag = 1;
static void sigHandler(int signum __attribute__((unused)))
{
loopFlag = 0;
}
static void cleanupCode(void)
{
printf("Graceful exit\n");
}
static void setSignals(void)
{
SigAction action;
sigfillset(&action.sa_mask);
action.sa_handler = sigHandler;
action.sa_flags = 0;
sigaction(SIGINT, &action, 0);
}
int main(void)
{
setSignals();
while (loopFlag)
sleep(600);
cleanupCode();
return(0);
}