1. 闹钟信号发送函数alarm:
头文件: #include <unistd.h>
函数原型: unsigned int alarm(unsined int seconds)
参数: seconds,指定秒数
返回值: 成功:如果调用此次alarm前,进程已经有闹钟时间,则返回上一个闹钟时间的剩余时间,否则0;
出错-1
2. alarm函数与raise函数比较:
相同点:让内核发送信号到当前进程
不同点:alarm只会发送SIGALARM信号;alarm会让内核定时一段时间后发送信号,raise会让内核立刻发送信号。
3. 常用信号及系统默认处理方式
信号名 |
含义 |
默认操作 |
SIGHUP |
该信号在用户终端连接(正常或非正常)结束时发出,通常是在终端的控制进程结束时,通知同一会话内的各个作业与控制终端不再关联。 |
终止 |
SIGINT |
该信号在用户键入INTR字符(通常是Ctrl-C)时发出,终端驱动程序发送此信号并送到前台进程中的每一个进程。 |
终止 |
SIGQUIT |
该信号和SIGINT类似,但由QUIT字符(通常是Ctrl-\)来控制。 |
终止 |
SIGILL |
该信号在一个进程企图执行一条非法指令时(可执行文件本身出现错误,或者试图执行数据段、堆栈溢出时)发出。 |
终止 |
SIGFPE |
该信号在发生致命的算术运算错误时发出。这里不仅包括浮点运算错误,还包括溢出及除数为0等其它所有的算术的错误。 |
终止 |
SIGKILL |
该信号用来立即结束程序的运行,并且不能被阻塞、处理和忽略。 |
终止 |
SIGALRM |
该信号当一个定时器到时的时候发出。 |
终止 |
SIGSTOP |
该信号用于暂停一个进程,且不能被阻塞、处理或忽略。 |
暂停进程 |
SIGTSTP |
该信号用于暂停交互进程,用户可键入SUSP字符(通常是Ctrl-Z)发出这个信号。 |
暂停进程 |
SIGCHLD |
子进程改变状态时,父进程会收到这个信号 |
忽略 |
SIGABORT |
该信号用于结束进程 |
终止 |
4. 实例1,alarm函数:
#include "stdio.h"
#include "sys/types.h"
#include "signal.h"
#include "stdio.h"
#include "stdlib.h"
int main()
{
int i;
i=0;
printf("alarm before\n");
alarm(9);
printf("alarm after\n");
while(i< 20)
{
i++;
sleep(1);
printf("process things,i=%d\n",i);
}
return 0;
}
执行结果:9s后终止进程
alex@alex-virtual-machine:/extra/process/008$ gcc alarm.c
ls
alex@alex-virtual-machine:/extra/process/008$ ls
alarm.c a.out pause.c
alex@alex-virtual-machine:/extra/process/008$ ./a.out
alarm before
alarm after
process things,i=1
process things,i=2
process things,i=3
process things,i=4
process things,i=5
process things,i=6
process things,i=7
process things,i=8
Alarm clock
alex@alex-virtual-machine:/extra/process/008$
5. 接收信号的进程具备条件:进程不能结束。
三种接收状态:
sleep:睡眠一段时间,状态S
pause:一直睡着,进程状态为S
while(1)
7. 进程接收函数pause
头文件: #include <unistd.h>
原型: int pause(void)
返回值: 成功0,出错-1
8. 示例二:pause:
#include "stdio.h"
#include "sys/types.h"
#include "signal.h"
#include "stdio.h"
#include "stdlib.h"
int main()
{
int i;
i=0;
printf("pause before\n");
pause();
printf("pause after\n");
while(i< 20)
{
i++;
sleep(1);
printf("process things,i=%d\n",i);
}
return 0;
}
执行结果,进程处于S状态:
4117 4701 4701 4117 pts/6 4701 S+ 1000 0:00 ./a.out
4044 4702 4702 4044 pts/5 4702 R+ 1000 0:00 ps -axj
alex@alex-virtual-machine:/extra/process$