Browse Source

file: faux_file_close() doesn't close fd opened by faux_file_fdopen() because fd was openen previously but not by faux_file code

Serj Kalichev 4 months ago
parent
commit
ebbd985efe
3 changed files with 25 additions and 6 deletions
  1. 22 6
      faux/file/file.c
  2. 1 0
      faux/file/private.h
  3. 2 0
      faux/testc_helpers/testc_helpers.c

+ 22 - 6
faux/file/file.c

@@ -32,7 +32,10 @@
 
 /** @brief Create file object using existent fd.
  *
- * Create file object and link it to existent file descriptor.
+ * Create file object and link it to existent file descriptor. The
+ * correspondent faux_file_close() will not really close the file because
+ * faux_file_fdopen() doesn't really open file but just link to existing
+ * fd.
  *
  * @param [in] fd Already opened file descriptor.
  * @return Allocated and initialized file object or NULL on error.
@@ -63,6 +66,7 @@ faux_file_t *faux_file_fdopen(int fd)
 	}
 	f->len = 0;
 	f->eof = BOOL_FALSE;
+	f->close_file = BOOL_FALSE; // Don't close fd because it's just a link
 
 	return f;
 }
@@ -84,6 +88,7 @@ faux_file_t *faux_file_fdopen(int fd)
 faux_file_t *faux_file_open(const char *pathname, int flags, mode_t mode)
 {
 	int fd = -1;
+	faux_file_t *f = NULL;
 
 	assert(pathname);
 	if (!pathname)
@@ -93,14 +98,23 @@ faux_file_t *faux_file_open(const char *pathname, int flags, mode_t mode)
 	if (fd < 0)
 		return NULL;
 
-	return faux_file_fdopen(fd);
+	f = faux_file_fdopen(fd);
+	if (!f) {
+		close(fd);
+		return NULL;
+	}
+	f->close_file = BOOL_TRUE;
+
+	return f;
 }
 
 
 /** @brief Closes file and frees file object.
  *
- * Function closes previously opened (by faux_file_open() or faux_file_fdopen())
- * file and frees file object structures.
+ * Function closes previously opened (by faux_file_open())
+ * file and frees file object structures. Note object initialized by
+ * faux_file_fdopen() will not really close fd because it was opened
+ * by another code previously.
  *
  * @param [in] f File object to close and free.
  * @return BOOL_TRUE - success, BOOL_FALSE - error
@@ -116,8 +130,10 @@ bool_t faux_file_close(faux_file_t *f)
 	faux_free(f->buf);
 	faux_free(f);
 
-	if (close(fd) < 0)
-		return BOOL_FALSE;
+	if (f->close_file) {
+		if (close(fd) < 0)
+			return BOOL_FALSE;
+	}
 
 	return BOOL_TRUE;
 }

+ 1 - 0
faux/file/private.h

@@ -11,4 +11,5 @@ struct faux_file_s {
 	size_t buf_size; // Current buffer size
 	size_t len; // Current data length
 	bool_t eof; // EOF flag
+	bool_t close_file; // Whether close the file on free function
 };

+ 2 - 0
faux/testc_helpers/testc_helpers.c

@@ -10,6 +10,7 @@
 #include <stdio.h>
 #include <stdarg.h>
 #include <errno.h>
+#include <unistd.h>
 
 #include "faux/ctype.h"
 #include "faux/str.h"
@@ -80,6 +81,7 @@ char *faux_testc_tmpfile_deploy(const void *buf, size_t len)
 
 	bytes_written = faux_file_write_block(f, buf, len);
 	faux_file_close(f);
+	close(fd);
 	if (bytes_written < 0)
 		return NULL;