2

I read about the signal manual page in signal(7) about "Interruption of system calls and library functions by signal handlers", I wonder what will happen if a signal generated when a write to disk is in the process, so I write a demo to test this kind of situation:

#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#define BUFFER_SIZE (1024 * 1024 * 1024)
char buffer[BUFFER_SIZE] = { 0 };
void handler(int num)
{
    char* message = "handler invoked for SIGINT\n";
    if (write(STDOUT_FILENO, message, strlen(message)) < strlen(message)) {
        perror("write to stdout error");
    }
}

int main(int argc, char* argv[])
{
    int fd;
    if ((fd = open("tempfile", O_CREAT | O_TRUNC | O_WRONLY | O_SYNC, S_IRWXG | S_IRWXO | S_IRWXU)) < 0) {
        perror("open error");
        return -1;
    }
    struct sigaction siga;
    siga.sa_handler = handler;
    sigaction(SIGINT, &siga, NULL);
    int count;
    while (1) {
        if ((count = write(fd, buffer, BUFFER_SIZE)) < BUFFER_SIZE) {
            printf("write filed with only %d bytes:%s\n", count, strerror(errno));
            break;
        } else {
            printf("write done with %d bytes\n", count);
        }
    }
    close(fd);
    return 0;
}

I found that a write to a disk can't be interrupted by signal which can be proved below: enter image description here I was trying to generate SIGINT through Ctrl+C, but write can't be interrupted until it writes all requested bytes to the disk. So, is a write to a disk not interruptable? And why?

cong
  • 1,105
  • 1
  • 12
  • 29
  • 1
    It's a kernel design decision. Some operations are not interruptible, and writes to disk are one such. All else apart, kernels think that you shouldn't leave the data on disk in an indeterminate state. At the level of a `write()` system call — which is associated with a specific process and might be user-interruptible, and distinct from the disk driver levels in the kernel, which are not associated with a single process and are not user-interruptible — the operation doesn't take long (mainly memory copying) so the interrupt is not handled until the write is returning to the user code. – Jonathan Leffler Sep 04 '17 at 16:21

0 Answers0