// 断言
#include // 结束状态处理
void handle_exit(int wstatus){
if(WIFEXITED(wstatus)){
// 正常结束,结束状态
printf("normal: %d\n",WEXITSTATUS(wstatus));
} else {
if(WIFSIGNALED(wstatus)){
// 信号状态
printf("abnormal: signal %d\n",WTERMSIG(wstatus));
}
}
}
// alarm 处理
void alarm_handle(int num){
printf("alarm_handle: %d\n",num);
alarm(1);
}
void int_handle(int num){
printf("int_handle: %d\n",num);
}
int main ()
{
//测试 1 wait 的使用
/*
int wstatus;
pid_t pid;
pid = fork();
assert(pid!=-1);
if(pid==0){
// son
exit(7);
} else {
wait(&wstatus);
handle_exit(wstatus);
}
pid = fork();
assert(pid!=-1);
if(pid==0){
// son
abort();
} else {
waitpid(pid, &wstatus, 0);
handle_exit(wstatus);
}
*/
//测试 2 信号的注册 发送信号
/*
int wstatus;
int pid = fork();
assert(pid!=-1);
if(pid==0){
// son
execv("./hello.out",NULL);
} else {
// father
sleep(1); // 睡眠一下,等待子进程完成信号的注册
kill(pid, SIGINT); //发送信号
waitpid(pid, &wstatus, 0);
handle_exit(wstatus);
}
*/
//测试 3 alarm循环
/*
signal(SIGALRM,alarm_handle);
alarm(1);
while(1)
pause();
*/
// 测试4 信号状态
/*
sigset_t old;
sigset_t new;
sigset_t pending;
// 注册 SIGINT 的处理函数
signal(SIGINT,int_handle);
// 读取并打印现在的状态字
sigprocmask(0,NULL,&old);
sigpending(&pending);
printf("读取并打印现在的状态字\n");
printf("block: %lu\n", sigismember(&old,SIGINT) );
printf("pendi: %lu\n", sigismember(&pending,SIGINT) );
// 阻塞 SIGINT
printf("\n阻塞 SIGINT\n");
sigemptyset(&new);
sigaddset(&new, SIGINT);
sigprocmask(SIG_BLOCK,&new,&old); //阻塞
sigprocmask(0,NULL,&old); //读取现在的状态
sigpending(&pending);
printf("block: %d\n", sigismember(&old,SIGINT) );
printf("pendi: %d\n", sigismember(&pending,SIGINT) );
// 给自己发送信号, 由于已经阻塞,不能处理
printf("\n给自己发送信号, 由于已经阻塞,不能处理\n");
raise(SIGINT);
sigprocmask(0,NULL,&old);
sigpending(&pending);
printf("block: %d\n", sigismember(&old,SIGINT) );
printf("pendi: %d\n", sigismember(&pending,SIGINT) );
sleep(1); //等待信号处理
// 解除阻塞
printf("\n解除阻塞\n");
sigprocmask(SIG_UNBLOCK,&new,&old);
sigpending(&pending);
printf("block: %d\n", sigismember(&old,SIGINT));
printf("pendi: %d\n", sigismember(&pending,SIGINT) );
sleep(1); //等待信号处理
*/
return 0;
}