如何覆盖(重置)SIGUSR1的默认行为?

mko*_*mko 0 c signals

我在信号处理函数中读到了关于add signal()函数可以覆盖的默认行为:

#include <stdio.h>
#include <signal.h>
#include <unistd.h>
void signalHandler();
int main(void) {
    signal(SIGUSR1, signalHandler);
    sleep(60);
    printf("I wake up");
    return 0;
}
void signalHandler() {
    signal(SIGUSR1, signalHandler);// I add this line to overwrite the default behaviour 
    printf("I received the signal");
}
Run Code Online (Sandbox Code Playgroud)

我用另一个进程触发它

#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {

    kill(5061, SIGUSR1); // 5061 is the receiver pid, kill(argv[1], SIGUSR1) doesn't working, when I get 5061 as parameter
    puts("send the signal ");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

接收器wake up接收SIGUSR1信号后立即接收处理.sleep即使接收到来自其他进程的信号,如何使接收器继续运行?

BTW为什么 kill(5061, SIGUSR1);5061是接收器pid,kill(argv[1], SIGUSR1)不起作用,当我得到5061作为参数?

Som*_*ude 5

sleep(3)手册页:

回报价值

如果请求的时间已经过去,则为零;如果呼叫被信号处理程序中断,则为剩余的秒数.

所以不要只是调用sleep你必须检查返回值并调用循环:

int sleep_time = 60;
while ((sleep_time = sleep(sleep_time)) > 0)
    ;
Run Code Online (Sandbox Code Playgroud)