2
#include <stdio.h>
#include <signal.h>
#include <fcntl.h>
#include <stdlib.h>

#define BUFSIZE 500*1024*1024
char buf[BUFSIZE];

static void sig_alrm(int signo) {
    printf("%d\n",time(NULL));
    printf("caught SIGALRM\n");
    fprintf(stderr, "in sig_alrm\n");
}


int main()
{
    int fd;
    fd=open("a.txt",O_WRONLY);
    signal(SIGALRM,sig_alrm);
    printf("%d\n",time(NULL));
    alarm(1);
    write(fd,buf,BUFSIZE);
}

output:

1414899972
1414899976
caught SIGALRM
in sig_alrm

It seems that the SIGALRM was caught about 3 seconds after the call to alarm(1). Why isn't the signal caught right away and the system call restarted?

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
Garrick_W
  • 23
  • 2
  • See [How to avoid using `printf()` in a signal handler?](http://stackoverflow.com/questions/16891019/how-to-avoid-using-printf-in-a-signal-handler/16891799#16891799) for a discussion on functions that can and cannot be called inside signal handlers. – Jonathan Leffler Nov 02 '14 at 05:47
  • @JonathanLeffler: Actually the use here is almost legal. The signal handler is not able to interrupt a non-async-signal-safe function, but happening during return from `main`, which is equivalent to `exit` which is non-AS-safe, should probably also be forbidden though the standard may miss this case. – R.. GitHub STOP HELPING ICE Nov 02 '14 at 06:45

1 Answers1

1

Some system calls don't allow interruptions. Writing to a local disk file is one of these. Writing to a file on an NFS server depends on whether it's mounted with the intr option (and I think this may only allow certain types of interrupts, such as Ctl-C).

Barmar
  • 741,623
  • 53
  • 500
  • 612