键盘信号处理,向回调处理函数添加参数(Ubuntu、intel)
我有这段代码:
#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;
}
有没有办法在回调函数中传递额外的参数? 比如:
#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;
}
谢谢你
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,没有,而且无论如何,您实际上应该在信号处理程序中做的事情很少。
我通常只是设置一个标志并返回,让真正的代码从那时起处理它。
如果您确实想这样做,您可以将
k
设为文件级静态,以便main
和信号处理程序(以及文件中的所有其他函数)都可以访问它,但您可能想研究该选项的安全性(信号处理程序是否可以在实际程序使用或更新该值时运行)。换句话说,类似:
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 bothmain
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).In other words, something like: