From 8d72ffe268305a823057053f6a172ac7debee3b0 Mon Sep 17 00:00:00 2001 From: Gediminas Jakutis Date: Sat, 15 Feb 2020 21:10:46 +0200 Subject: add a wrapper for closing files. Signed-off-by: Gediminas Jakutis --- src/io.c | 36 ++++++++++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-) (limited to 'src/io.c') diff --git a/src/io.c b/src/io.c index 74ea274..142e230 100644 --- a/src/io.c +++ b/src/io.c @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -9,16 +10,14 @@ #include #include "io.h" -int openstream(struct stream *in) +int stream_open(struct stream *in) { struct stat st; mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP; char *dname = NULL; int ret = 0; - in->fd = -1; - - if (!in->name) { + if (!in || in->fd > 0 || !in->name) { ret = EINVAL; goto err; } @@ -89,3 +88,32 @@ err: free(dname); return ret; } + +int stream_close(struct stream *in) +{ + char path[PATH_MAX]; + int ret = 0; + + if (!in || in->fd < 0) { + ret = EINVAL; + goto early_err; + } + + if (in->out && in->name) { + snprintf(path, PATH_MAX, "/proc/self/fd/%i", in->fd); + if (linkat(AT_FDCWD, path, AT_FDCWD, in->name, AT_SYMLINK_FOLLOW)) { + ret = errno; + /* TODO: error message */ + goto err; + } + } else { + ret = EINVAL; + goto err; + } + +err: + close(in->fd); + in->fd = -1; +early_err: + return ret; +} -- cgit v1.2.3