printf("SIGUSR1 is now blocked. Sleeping for 5 seconds...\n"); sleep(5); // 在这5秒内,SIGUSR1会被阻塞,SIGINT不会
//4. 演示 SIG_SETMASK: 只阻塞 SIGINT,解除对 SIGUSR1 的阻塞 sigemptyset(&block_set); sigaddset(&block_set, SIGINT); // 现在只阻塞 SIGINT printf("5 seconds passed. Now blocking only SIGINT (Ctrl+C) using SIG_SETMASK.\n"); printf("Try sending SIGUSR1 now: 'kill -USR1 %d' - it should be caught immediately.\n"); printf("Try pressing Ctrl+C (SIGINT) now - it should be blocked.\n"); if (sigprocmask(SIG_SETMASK, &block_set, NULL) == -1) { // 设置新的屏蔽字 perror("sigprocmask SETMASK"); exit(EXIT_FAILURE); }
printf("SIGINT is now blocked. Sleeping for 5 more seconds...\n"); sleep(5); // 在这5秒内,SIGINT会被阻塞,SIGUSR1不会
//5. 演示 SIG_UNBLOCK: 解除对 SIGINT 的阻塞 // 我们解除阻塞的集合就是当前阻塞的集合 (block_set) printf("5 seconds passed. Now unblocking SIGINT (Ctrl+C) using SIG_UNBLOCK.\n"); printf("Try pressing Ctrl+C (SIGINT) now - it should work and terminate the program.\n"); if (sigprocmask(SIG_UNBLOCK, &block_set, NULL) == -1) { // 解除阻塞 perror("sigprocmask UNBLOCK"); exit(EXIT_FAILURE); }
printf("SIGINT is now unblocked. Sleeping for 10 more seconds...\n"); printf("The program will end if you press Ctrl+C.\n"); sleep(10); // 最后10秒,所有信号都按正常处理
printf("Program exiting normally after sleep.\n"); return 0; }