今天主要讲线程中信号的三个函数
1.pause
1.pauseint pause(void);
功能:让进程睡眠,直到接收到信号(捕捉)才能继续向下执行
eg:
#include "head.h"void handler(int signo)
{return;
}int main(void)
{signal(SIGINT,handler);printf("pause up!\n");pause();printf("pause down!\n");return 0;
}
运行结果:
可以看到,必须得要等到信号捕捉到了,必须是捕捉信号!才会向下执行。
2.alarm
2.alarmunsigned int alarm(unsigned int seconds);功能:定时seconds秒后给调用进程发送SIGALRM信号参数:seconds:定时的秒数返回值:成功返回之前设定剩余的秒数
eg:
#include"head.h"void handler(int signo)
{printf("The signal is coming.\n");alarm(5);return;
}int main(void)
{signal(SIGALRM,handler);alarm(5);while(1){printf("Process sequential execution!\n");sleep(1);}return 0;
}
运行结果:
我们将alarm信号从缺省变成了捕捉,从而当alarm结束时,我们又重新发起了该信号进行处理。
3.kill
3.killint kill(pid_t pid, int sig);
功能:给PID对应的进程发送sig信号
参数:pid:进程ID号sig:信号的编号
返回值:成功返回0 失败返回-1
eg:
#include"head.h"pid_t pid;void handler_child(int signo)
{if(SIGINT == signo){printf("father,i am comming home!\n");kill(getppid(),SIGUSR1); //向父进程发送信号,SIGUSR1为用户自定义信号}else if(SIGUSR2 == signo){printf("quickly cook!\n");}
}void handler_father(int signo)
{if(SIGUSR1 == signo){printf("quickly do homework!\n");}else if(SIGQUIT == signo){printf("son,i am comming home!\n");kill(pid,SIGUSR2);}
}int main(void)
{pid = fork();if(-1 == pid){perror("fail to fork");return -1;}if(0 == pid){signal(SIGQUIT,SIG_IGN);signal(SIGINT,handler_child);signal(SIGUSR2,handler_child);}else if(pid > 0){signal(SIGINT,SIG_IGN); //忽略SIGINT(ctrl+c)信号signal(SIGUSR1,handler_father); //自定义SIGUSR1信号,当子进程发送该信号,做处理signal(SIGQUIT,handler_father); //与上面差不多}while(1){}return 0;
}
结果: