gpt4 book ai didi

C 循环等待信号

转载 作者:太空宇宙 更新时间:2023-11-04 09:58:12 24 4
gpt4 key购买 nike

在 C Linux 中,有没有什么方法可以不循环地等待 SIGUSR1SIGUSR2 之类的信号?

对于此代码中的示例,我等待 SIGUSR1SIGUSR2 打印消息,但是当我想要时,我会在 true 时执行....

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

void signal_callback_handler(int signum)
{
printf("Caught signal %d\n",signum);
}

int main()
{
signal(SIGUSR1, signal_callback_handler);
signal(SIGUSR2, signal_callback_handler);
while(1)
{
printf("Program processing stuff here.\n");
sleep(1);
}
return EXIT_SUCCESS;
}

SIGUSR1SIGUSR2 到达之前,我如何等待并且不做任何事情(不做任何事情)?

例如:

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

void signal_callback_handler(int signum)
{
printf("Caught signal %d\n",signum);
}

int main()
{
signal(SIGUSR1, signal_callback_handler);
signal(SIGUSR2, signal_callback_handler);

printf("this line happned after signal arrived \n ");
return EXIT_SUCCESS;
}

最佳答案

有两种可能:

  • pause()
  • sigwait()

pause 的文档:

Description
pause() causes the calling process (or thread) to sleep until a signal is delivered that either terminates the process or causes the invocation of a signal-catching function.

来源:https://linux.die.net/man/2/pause


以及 sigwait 的文档:

Description
The sigwait() function suspends execution of the calling thread until one of the signals specified in the signal set set becomes pending. The function accepts the signal (removes it from the pending list of signals), and returns the signal number in sig.

来源:https://linux.die.net/man/3/sigwait

这两个函数都符合POSIX.1-2001

关于C 循环等待信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58427667/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com