C中的Sigaction处理程序

时间:2018-11-07 20:02:55

标签: c shell unix process signals

我们有一个作业来解释这段代码。我唯一的问题是了解handle_signal函数,为什么我们使用2个新sigaction,然后将“ old_treatment”与“ rien”一起使用?

#define DELAY 1
#define NB_ITERATIONS 60
void handle_signal (int num_signal){
    struct sigaction rien, old_ treatment;
    printf ("Signal %d => ", num_signal);
    printf ("I have received a SIGTSTP.\n");
    rien.sa_handler = SIG_DFL;
    rien.sa_flags = 0;
    sigemptyset (&rien.sa_mask);
    sigaction (SIGTSTP, &rien, &old_ treatment);
    printf ("Then I sleep....\n");
    kill (getpid(), SIGSTOP);
    printf ("They wakes me?\n");
    Sigaction (SIGTSTP, &old_ treatment, NULL);
    printf ("Here we go again!\n");
}

int main (void){
    struct sigaction a;
    int i;
    a.sa_handler = handle_signal;
    sigemptyset (&a.sa_mask);
    sigaction (SIGTSTP, &a, NULL);
    for (i = 1; i < NB_ITERATIONS; i++) {
    sleep (DELAY);
    printf ("%d", i % 10);
    fflush (stdout);}
    printf ("End\n");
    return EXIT_SUCCESS;
}

1 个答案:

答案 0 :(得分:1)

此操作的目的是暂时更改SIGTSTP的操作,然后将其恢复。

sigaction(SIGTSTP, &rien, &old_handler);

将其设置为默认操作,并将上一个操作保存在old_handler中。

然后,它会向自己发送一个SIGSTOP信号以实际中止该过程。

当返回时,表示该过程已继续,因此将旧操作放回去:

sigaction(SIGTSTOP, &old_handler, NULL);

目前尚不清楚为什么需要这样做。如果它通过发送SIGTSTP而不是SIGSTOP信号来中止进程,那将更有意义。在这种情况下,它需要设置默认操作,否则它将无限递归。

相关问题