为什么 explain_fwrite 说我的文件标记为非阻塞?

Why is explain_fwrite saying my file marked as non-blocking?

我正在尝试将一些数据写入文件。 fwrite 返回 EAGAIN 并且 fwrite_explain 说:

2: fwrite(ptr = 0x7F41EFBC09A8, size = 4066, nmemb = 1, fp = 0x02F79200 "/home/user/asdf.txt") failed, Resource temporarily unavailable (11, EAGAIN) because the file descriptor has been marked non-blocking (O_NONBLOCK) and the write would block
2: fwrite(ptr = 0x17ECFFA40, size = 4066, nmemb = 1, fp = 0x02F79200 "/home/user/asdf.txt") failed, No such file or directory (2, ENOENT) because the file is on a file system ("/home", 1% full) which does not support Unix open file semantics, and the file has been deleted from underneath you
2: fwrite(ptr = 0x17ECFF100, size = 4066, nmemb = 1, fp = 0x02F79200 "/home/user/asdf.txt") failed, No such file or directory (2, ENOENT) because the file is on a file system ("/home", 1% full) which does not support Unix open file semantics, and the file has been deleted from underneath you

我假设第二组警告无效(文件从未被删除,它仍然存在)。

我从来没有将我的文件设置为非阻塞,我也不关心它是否阻塞,因为我想写入数据,而不管它可能需要多长时间。给出了什么?

相关代码:

fd = fopen(file_to_write, "w");
if (fd == NULL) printf("%d could not open file\n", errno);
n = fwrite((void*)h->bufs[i], write_size, 1, fd);
if (n != write_size) {
    printf("%d: %s\n", errno, explain_fwrite((void*)h->bufs[i], write_size, 1, fd));

我在发布的过程中设法解决了这个问题。事实证明 fwrite 对 size 和 nmemb 的顺序和内容很挑剔。我想我可以写 one really big 成员,但事实并非如此。我必须写 write_size 个成员,每个成员的大小为一个字节。

fwrite() returns 写入的 items 的数量,而不是一个项目的 size 或两者的产物。 (只有一项的大小恰好为1时,return值才等于写入的字节数。)

解决方案是与您尝试写入的项目数进行比较:

n = fwrite((void*)h->bufs[i], write_size, 1, fd);
if (n != 1) {

注意:在调用之前将 errno 设置为零可能是明智的,因为如果函数没有错误,它不会设置为零。