当读文件时,另一个进程把文件长度置0,会发生......
读进程:
cat r.c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main() {
int fd = open("test.txt", O_RDONLY);
if (fd == -1) { perror("open fail"); return -1; }
char buf[2] = {0}; // 每次读1个字节
int n;
printf("开始读取文件,持续输出读取内容:\n");
// 循环读取,直到read返回0
while ((n = read(fd, buf, 1)) > 0) {
printf("读到:%c (ASCII: %d)\n", buf[0], buf[0]);
usleep(500000); // 每次读暂停0.5秒,方便手动执行截断进程
}
printf("读取结束,read返回值:%d(EOF)\n", n);
close(fd);
return 0;
}
写进程
cat w2.c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd = open("test.txt", O_WRONLY);
if (fd == -1) { perror("open fail"); return -1; }
// 核心操作:将文件长度强制置为0
int ret = ftruncate(fd, 0);
if (ret == 0) {
printf("✅ 成功将文件长度置为0(截断文件)\n");
} else {
perror("截断文件失败");
}
close(fd);
return 0;
}
执行结果:

浙公网安备 33010602011771号