EMBEDDED/SYSTEM Proc

[Signal] sigprocmask() 관련 예제

몰라욧 2012. 7. 13. 16:30

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

main()
{
    sigset_t set1, set2;

    /* 꽉 찬 시그널 집합 set1 생성 */
    sigfillset(&set1);
    sigemptyset(&set2);
    /* SIGINT를 원소로 하는 시그널 집합 set2 */
    sigaddset(&set2, SIGINT);

    /* 모든 시그널에 블록 설정 */
    sigprocmask(SIG_BLOCK, &set1, NULL);
    printf("block start\n");
    sleep(10);
    /* SIGINT 시그널은 블록에서 해제 */
    sigprocmask(SIG_UNBLOCK, &set2, NULL);
    printf("SIGINT unblock\n");
    while(1) {
       printf("Hello World\n");
       sleep(2);
    }
}

[localhost@local]#a.out
block start
^\ --> 블록화됨
sigint wake up
^\ --> 블록화됨
Hello World
^c --> 프로세스 종료됨

[localhost@local]#a.out
block start
^c --> 블록화되었다가 해제되면 프로세스 종료됨


-------------------------------------------------------------------------------------------------------
시그널을 블록화했다가 원상태로 되돌리는 예제

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

main()
{
    sigset_t set, oldset;

    sigemptyset(&set);
    sigaddset(&set, SIGINT);

    /* SIGINT에 대해 블록 설정하고 이전 블록화 된 시그널 집합을 oldset에 저장 */
    sigprocmask(SIG_BLOCK, &set, &oldset);
    printf("block start\n");
    sleep(10);
    /* oldset의 시그널들이 블록화 된 시그널 집합으로 교체 */
    sigprocmask(SIG_SETMASK, &oldset, NULL);
    printf("restore to the original state\n");
    while(1) {
       printf("Hello World\n");
       sleep(2);
    }
}