信号是异步的,它会在程序的任何地方发生。由此程序正常的执行路径被打破,去执行信号处理函数。一般情况下,进程正在执行某个系统调用,那么在该系统调用返回前信号是不会被递送的。但慢速系统调用除外,如读写终端、网络、磁盘,以及wait和pause。这些系统调用都会返回-1,errno置为EINTR。当系统调用被中断时,我们可以选择使用循环再次调用,或者设置重新启动该系统调用(SA_RESTART)。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>
#include <signal.h>
#include <sys/types.h>
#include <errno.h>
#include <string.h>
void int_handler (int signum)
{
printf ("int handler %d\n",signum);
}
int main(int argc, char **argv)
{
char buf[100];
ssize_t ret;
struct sigaction oldact;
struct sigaction act;
act.sa_handler = int_handler;
act.sa_flags=0;
act.sa_flags |= SA_RESTART;
sigemptyset(&act.sa_mask);
if (-1 == sigaction(SIGINT,&act,&oldact))
{
printf("sigaction failed!\n");
return -1;
}
bzero(buf,100);
ret = read(STDIN_FILENO,buf,10);
if (ret == -1)
{
printf ("read error %s\n", strerror(errno));
}
printf ("read %d bytes, content is %s\n",ret,buf);
sleep (10);
return 0;
}
^Cint handler 2
^Cint handler 2
^Cint handler 2
^Cint handler 2
^Cint handler 2
^Cint handler 2
hgfd
read 5 bytes, content is hgfd
把程序不用SA_RESTART:
结果
^Cint handler 2
read error Interrupted system call
read -1 bytes, content is
程序立即结束啦。
http://blog.csdn.net/ccccdddxxx/article/details/6308381