void (*signal(int signum, void (*func)(int)))(int)
使用sighandler_t容易造成名字空间冲突,所以还是使用上述定义方式;
ctrl+c 等于 SIGINT 终端中断符
忽略信号
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
int main()
{
int i = 0;
//signal (SIGINT, SIG_IGN);//忽略Ctrl+C
for (i = 0; i < 10; i++)
{
printf ("*");
sleep(1);
}
exit (0);
}
为信号注册动作
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
void sig_handler(int s)
{
printf ("SIGINT-handler %d\n", s);
}
int main()
{
int i = 0;
signal (SIGINT, sig_handler);
getchar();
exit (0);
}
信号会打断阻塞的系统调用,比如sleep时如果有信号到来可以打断sleep,如果打开一些比较慢的设备时就可能被信号打断
防止打开慢速设备时被信号打断
do
{
fd = open(argv[1], O_RDONLY);
if (fd < 0)
{
if (errno != EINTR)//等待过程中被信号打断就返回EINTR
{
perror ("open()");
exit (1);
}
}
}while(fd < 0);
可重入
alarm不能累加会以最后一个为准
int main()
{
alarm(10);
alarm(1);
alarm(5);//代码执行结果是5s后退出
exit (0);
}
fork exec wait
exec()族之前必须要fflush(NULL)