简体   繁体   English

键盘信号处理,向回调处理函数添加参数(Ubuntu,intel)

[英]Keyboard signal handling, adding parameters to callback handler function (Ubuntu, intel)

I have this code: 我有这个代码:

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

// Define the function to be called when ctrl-c (SIGINT) signal is sent to process
void
signal_callback_handler(int signum)
{
   printf("Caught signal %d\n",signum);
   // Cleanup and close up stuff here

   // Terminate program
   exit(signum);
}

int main()
{
   // Register signal and signal handler
   signal(SIGINT, signal_callback_handler);

   while(1)
   {
      printf("Program processing stuff here.\n");
      sleep(1);
   }
   return EXIT_SUCCESS;
}

Is there a way to pass an extra argument in the callback function? 有没有办法在回调函数中传递额外的参数? Something like: 就像是:

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

// Define the function to be called when ctrl-c (SIGINT) signal is sent to process
void
signal_callback_handler(int signum, int k)
{

   k++; // Changing value of k
}

int main()
{
   int k = 0;
   // Register signal and signal handler
   signal(SIGINT, signal_callback_handler(k);

   while(1)
   {
      printf("Program processing stuff here.\n");
      printf(" blah %d\n", k);
      sleep(1);
   }
   return EXIT_SUCCESS;
}

Thank you 谢谢

No, there's not, and there's very little that you should actually be doing in a signal handler anyway. 不,没有,而且无论如何你应该在信号处理程序中做的很少。

I generally just set a flag and return, letting the real code handle it from then on. 我通常只是设置一个标志并返回,让真正的代码从此处理它。

If you really wanted to do that, you could make k a file-level static so that both main and the signal handler (and every other function in the file) could access it, but you might want to investigate the safety of that option (whether a signal handler can run while the real program is using or updating the value). 如果你真的想这样做,你可以使k成为文件级静态,以便main和信号处理程序(以及文件中的所有其他函数)都可以访问它,但是你可能想要调查该选项的安全性(在真实程序使用或更新值时是否可以运行信号处理程序)。

In other words, something like: 换句话说,像:

static int k = 0;

void signal_callback_handler(int signum) {
   k++; // Changing value of k
}

int main() {
   // Register signal and signal handler
   signal(SIGINT, signal_callback_handler);
   : :

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

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