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:
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?