open 与 fopen一个文件并正常写入, 删除文件不报错
代码如下:
open.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
int main()
{
int fd = open("open.txt", O_RDWR | O_CREAT);
int nwrite = 0;
while(1)
{
sleep(1);
nwrite = write(fd, "open test\n", sizeof("open test\n"));
if (nwrite < 0) {
printf("%d : %s", errno, strerror(errno));
} else {
printf("write open ok\n");
}
}
close(fd);
}
编译后执行,显示结果。过一会删除文件后,仍旧是继续写文件,屏幕打印一直持续
fopen.c也是
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
int main()
{
FILE *fp = fopen("./fopen.txt", "ab+");
int n_write = 0;
while(1)
{
n_write = fwrite("test\n", 6, 1, fp);
if (n_write < 0) {
printf("[%d] : %s\n", errno, strerror(errno));
} else {
printf("write ok\n");
}
sleep(1);
fflush(fp);
}
fclose(fp);
}
编译后执行,显示结果。过一会删除文件后,仍旧是继续写文件,屏幕打印一直持续
这是系统bug?哪些参数可以捕捉?居然不会报错。于是查找一下进程号。去进程号里面看信息
查看进程信息
[root@localhost Ctest]# ps -e | grep fopen
37886 pts/2 00:00:00 fopen
进入到对应进程节点目录下,显示信息如下
[root@localhost Ctest]# cd /proc/37886/
[root@localhost 37886]# cd fd
[root@localhost fd]# ls -la
total 0
dr-x------. 2 root root 0 Sep 28 23:16 .
dr-xr-xr-x. 9 root root 0 Sep 28 23:15 ..
lrwx------. 1 root root 64 Sep 28 23:16 0 -> /dev/pts/2
lrwx------. 1 root root 64 Sep 28 23:16 1 -> /dev/pts/2
lrwx------. 1 root root 64 Sep 28 23:16 2 -> /dev/pts/2
lrwx------. 1 root root 64 Sep 28 23:16 3 -> /home/workspace/code/Ctest/fopen.txt (deleted)
删除前
[root@localhost fd]# ps -e | grep fopen
40896 pts/2 00:00:00 fopen
[root@localhost fd]# cd /proc/40896/
[root@localhost 40896]# cd fd
[root@localhost fd]# ls
0 1 2 3
[root@localhost fd]# ls -la
total 0
dr-x------. 2 root root 0 Sep 28 23:17 .
dr-xr-xr-x. 9 root root 0 Sep 28 23:17 ..
lrwx------. 1 root root 64 Sep 28 23:17 0 -> /dev/pts/2
lrwx------. 1 root root 64 Sep 28 23:17 1 -> /dev/pts/2
lrwx------. 1 root root 64 Sep 28 23:17 2 -> /dev/pts/2
lrwx------. 1 root root 64 Sep 28 23:17 3 -> /home/workspace/code/Ctest/fopen.txt
删除后
[root@localhost fd]# rm /home/workspace/code/Ctest/fopen.txt -f
[root@localhost fd]# ls -la
total 0
dr-x------. 2 root root 0 Sep 28 23:17 .
dr-xr-xr-x. 9 root root 0 Sep 28 23:17 ..
lrwx------. 1 root root 64 Sep 28 23:17 0 -> /dev/pts/2
lrwx------. 1 root root 64 Sep 28 23:17 1 -> /dev/pts/2
lrwx------. 1 root root 64 Sep 28 23:17 2 -> /dev/pts/2
lrwx------. 1 root root 64 Sep 28 23:17 3 -> /home/workspace/code/Ctest/fopen.txt (deleted)
[root@localhost fd]#
在使用时可以加一个access判断文件夹是否存在。也可以试试flock。这个还没有验证过。网上看的介绍是多进程操作锁。照理来说,就是可以的。