diff mbox series

[v2,13/15] arch: sandbox: Add function to create temporary files

Message ID 20231104203753.1579217-14-seanga2@gmail.com
State Accepted
Commit 9181cb0507d1dd5627cc3d9cd86d427abe00cc21
Delegated to: Dario Binacchi
Headers show
Series nand: Add sandbox tests | expand

Commit Message

Sean Anderson Nov. 4, 2023, 8:37 p.m. UTC
When working with sparse data buffers that may be larger than the address
space, it is convenient to work with files instead. Add a function to create
temporary files of a certain size.

Signed-off-by: Sean Anderson <seanga2@gmail.com>
---

(no changes since v1)

 arch/sandbox/cpu/os.c | 17 +++++++++++++++++
 include/os.h          | 13 +++++++++++++
 2 files changed, 30 insertions(+)
diff mbox series

Patch

diff --git a/arch/sandbox/cpu/os.c b/arch/sandbox/cpu/os.c
index 85d0d6a1703..8847c4cd0a8 100644
--- a/arch/sandbox/cpu/os.c
+++ b/arch/sandbox/cpu/os.c
@@ -282,6 +282,23 @@  int os_persistent_file(char *buf, int maxsize, const char *fname)
 	return 0;
 }
 
+int os_mktemp(char *fname, off_t size)
+{
+	int fd;
+
+	fd = mkostemp(fname, O_CLOEXEC);
+	if (fd < 0)
+		return -errno;
+
+	if (unlink(fname) < 0)
+		return -errno;
+
+	if (ftruncate(fd, size))
+		return -errno;
+
+	return fd;
+}
+
 /* Restore tty state when we exit */
 static struct termios orig_term;
 static bool term_setup;
diff --git a/include/os.h b/include/os.h
index fc8a1b15cbf..877404a6c13 100644
--- a/include/os.h
+++ b/include/os.h
@@ -108,6 +108,19 @@  int os_unlink(const char *pathname);
  */
 int os_persistent_file(char *buf, int maxsize, const char *fname);
 
+/**
+ * os_mktemp() - Create a temporary file
+ * @fname: The template to use for the file name. This must end with 6 Xs. It
+ *         will be modified to the opened filename on success.
+ * @size: The size of the file
+ *
+ * Create a temporary file using @fname as a template, unlink it, and truncate
+ * it to @size.
+ *
+ * Return: A file descriptor, or negative errno on error
+ */
+int os_mktemp(char *fname, off_t size);
+
 /**
  * os_exit() - access to the OS exit() system call
  *