我读到了信号(7)中关于"信号处理程序"中断系统调用和库函数的信号手册页,我想知道当写入磁盘时产生的信号会发生什么这个过程,所以我写了一个演示来测试这种情况:
#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;
}
我发现对磁盘的写入不能被信号中断,这可以在下面证明: 我试图通过Ctrl + C生成SIGINT,但写入不能被中断,直到它将所有请求的字节写入磁盘。那么,写入磁盘是不是可中断的?为什么?